您的位置:首页 > 数据库

SQL SERVER 強制指定使用索引 -转载 只为学习

2013-07-12 14:55 225 查看
今天很高兴 ,有学会了一种数据库优化的方式,哈哈

今天遇到一個查詢逾時的問題:兩段SQL,只差在WHERE,一個是WHERE COLUMN1='AAA',一個是WHERE COLUMN1='BBB',產生的執行計畫卻不一樣;一個用PK索引,一個用IX索引(叢集索引跟非叢集索引的差別?)

查到兩種方法,INDEX()跟FORCESEEK

INDEX('指定索引名稱')

FORCESEEK 指定從哪個資料表搜尋

--系統會自動選用IX_index
select count(1)
from table1 a with(nolock)
join table2 b with(nolock) on a.key_col=b.key_col
where b.some_col='aaa'

--系統會自動選用PK_index
select count(1)
from table1 a with(nolock)
join table2 b with(nolock) on a.key_col=b.key_col
where b.some_col='bbb'

--指定使用PK_index
select count(1)
from table1 a with(nolock)
join table2 b with(nolock,, INDEX( PK_table2 )) on a.key_col=b.key_col
where b.some_col='aaa'

--沒實際用成功過,不知是否有效,資料庫相容性模式要設為90
select count(1)
from table1 a with(nolock)
join table2 b with(FORCESEEK) on a.key_col=b.key_col
where b.some_col='aaa'
參考資料:
http://msdn.microsoft.com/zh-tw/library/bb677261.aspx http://msdn.microsoft.com/zh-tw/library/bb510478.aspx
DotBlogs Tags: T-SQL
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: