SQL SERVER 强制指定使用索引
今天遇到一个查询逾时的问题:两段SQL,只差在WHERE,一个是WHERE COLUMN1='AAA',一个是WHERE COLUMN1='BBB',产生的执行计划却不一样;一个用PK索引,一个用IX索引(丛集索引跟非丛集索引的差别?)
查到两种方法,INDEX()跟FORCESEEK
- INDEX('指定索引名称')
- FORCESEEK 指定从哪个数据表搜寻
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