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

今天很高兴 ,有学会了一种数据库优化的方式,哈哈

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

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

  1. INDEX('指定索引名稱')
  2. 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 

你可能感兴趣的:(SQL Server)