I have a query of the form
SELECT DISTINCT Str,Score
FROM Tab
WHERE Str in ('Str1', 'Str2', 'Str3') AND Type = 0
Table schema is
Str - varchar(8000)
Score - int
Type - bit
I also have an index on Str
which includes Type
and Score
The number of strings in the IN
vary
When I construct a direct query from C#, it's virtually instantaneous
When I use a parametrized query (using the method here https://stackoverflow.com/a/337792/508593 ), it becomes extremely slow -- the original query takes less than a second. This is timing out
Looking into SQL profiler and SSMS, the slowness seems to be due to the statement being wrapped in exec sp_executesql
which causes an index scan instead of a seek. The direct query uses the index mentioned. With sp_executesql
, the index does not
Is my suspicion correct and is there a way to resolve this?
In addition to the root cause specified by Martin, the solution was to explicitly set the parameter type using
command.Parameters[i].DbType = DbType.AnsiString;
Which forces varchar instead of nvarchar