Saturday, February 25, 2012

Query not use Index

I have a table with name "tbl_Test" in a SQL Server 2000 with many milion records.

A column of this table is "LASTNAME". (varchar (30))

I have make a Index of this column.

The query

DECLARE @.e varchar(30)

SET @.e = 'message%'

SELECT * FROM tbl_Test WHERE LASTNAME LIKE @.e

not use the index. (I have the result in 2 minute, 'table scan')

The query

SELECT * FROM tbl_Test WHERE LASTNAME LIKE 'message%'

use the index. (I have the result in 2 second, 'Index seek')

The query

DECLARE @.e varchar(30)

SET @.e = 'message'

SELECT * FROM tbl_Test WHERE LASTNAME = @.e

use the index. (I have the result in 1 second, 'Index seek')

I want to make a parametirize query with operator LIKE, where use the index. HOW ?

To make a parameterized search, you ought to read this article by Erland Sommarskog:

http://www.sommarskog.se/dyn-search.html

There are several things going on with your different versions of the query and why index usage switches on and off in some cases. For one thing, there are times in which the optimizer SHOULD decide to use a table scan instead of an index seek. You might want to give this article a look:

http://www.microsoft.com/technet/prodtechnol/sql/2005/recomp.mspx

Also, here are a couple of posts that discuss "plan crossover:"

http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=1182412&SiteID=1
http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=1317279&SiteID=1

Keep in mind that the optimizer is more likely to use the index when it is dealing with a constant -- such as 'message%' instead of a variable such as @.e. Also, the optimizer is more likely to "choose" the index path if it is an EQUAL join as apposed to a LIKE join.

No comments:

Post a Comment