Please start any new threads on our new
site at https://forums.sqlteam.com. We've got lots of great SQL Server
experts to answer whatever question you can come up with.
| Author |
Topic |
|
_jesse
Starting Member
1 Post |
Posted - 2008-05-08 : 11:30:08
|
| This seems to be a classic parameter-sniffing problem -- except that I can't seem to force the query to run with the correct plan. The proc below tries to just select using LIKE. When I use a literal string predicate, I get a nice, fast index seek. All of the other variants do an index scan -- of the wrong index.What else can I do to force SQL Server to use the correct index?DROP PROCEDURE test_likeGOCREATE PROCEDURE test_like@searchText nvarchar(64)AS-- Straight literal string search. Runs quickly with index seek on companies.searchbrandSELECT companyIdFROM companiesWHERE searchbrand LIKE 'adv%'-- Each of the queries below does an index scan on the primary key index on companies.companyId-- instead of doing a seek on the correct index.-- Search for proc parameterSELECT companyIdFROM companiesWHERE searchbrand LIKE @searchText-- Search for proc parameter, with hintSELECT companyIdFROM companiesWHERE searchbrand LIKE @searchTextOPTION ( OPTIMIZE FOR (@searchText = 'adv%') )-- Local variableDECLARE @localText nvarchar(64)SET @localText = @searchTextSELECT companyIdFROM companiesWHERE searchbrand LIKE @localTextGOEXEC test_like 'adv%' |
|
|
sanoj_av
Posting Yak Master
118 Posts |
Posted - 2008-05-09 : 06:29:08
|
You can force SQL Server to use a specified index.for Example,SELECT companyIdFROM companieswith (INDEX (your_index_name))WHERE searchbrand LIKE @searchTextquote: Originally posted by _jesse This seems to be a classic parameter-sniffing problem -- except that I can't seem to force the query to run with the correct plan. The proc below tries to just select using LIKE. When I use a literal string predicate, I get a nice, fast index seek. All of the other variants do an index scan -- of the wrong index.What else can I do to force SQL Server to use the correct index?DROP PROCEDURE test_likeGOCREATE PROCEDURE test_like@searchText nvarchar(64)AS-- Straight literal string search. Runs quickly with index seek on companies.searchbrandSELECT companyIdFROM companiesWHERE searchbrand LIKE 'adv%'-- Each of the queries below does an index scan on the primary key index on companies.companyId-- instead of doing a seek on the correct index.-- Search for proc parameterSELECT companyIdFROM companiesWHERE searchbrand LIKE @searchText-- Search for proc parameter, with hintSELECT companyIdFROM companiesWHERE searchbrand LIKE @searchTextOPTION ( OPTIMIZE FOR (@searchText = 'adv%') )-- Local variableDECLARE @localText nvarchar(64)SET @localText = @searchTextSELECT companyIdFROM companiesWHERE searchbrand LIKE @localTextGOEXEC test_like 'adv%'
|
 |
|
|
|
|
|