I have this query :
select top 100 id, email, amount from view_orders
where email LIKE '%test%' order by created_at desc
It takes less than a second to run.
Now I want to parameterize it :
declare @m nvarchar(200)
set @m = '%test%'
SELECT TOP 100 id, email, amount FROM view_orders
WHERE email LIKE @m ORDER BY created_at DESC
After 5 minutes, it's still running. With any other kind of test on parameters (if I replace the "like" with "="), it falls down to the first query level of performance.
I am using SQL Server 2008 R2.
I have tried with OPTION(RECOMPILE)
, it drops to 6 seconds, but it's still much slower (the non-parameterized query is instantaneous). As it's a query that I expect will be run often, it's an issue.
The table's column is indexed, but the view is not, I don't know if it can make a difference.
The view joins 5 tables : one with 3,154,333 rows (users), one with 1,536,111 rows (orders), and 3 with a few dozen rows at most (order type, etc). The search is done on the "user" table (with 3M rows).
Hard-coded values :
Parameters :
Update
I have run the queries using SET STATISTICS IO ON
. Here are the result (sorry I don't know how to read that) :
Hard-coded values:
Table 'currency'. Scan count 1, logical reads 201.
Table 'order_status'. Scan count 0, logical reads 200.
Table 'payment'. Scan count 1, logical reads 100.
Table 'gift'. Scan count 202, logical reads 404.
Table 'order'. Scan count 95, logical reads 683.
Table 'user'. Scan count 1, logical reads 7956.
Parameters :
Table 'currency'. scan count 1, logical reads 201.
Table 'order_status'. scan count 1, logical reads 201.
Table 'payment'. scan count 1, logical reads 100.
Table 'gift'. scan count 202, logical reads 404.
Table 'user'. scan count 0, logical reads 4353067.
Table 'order'. scan count 1, logical reads 4357031.
Update 2
I have since seen a "force index usage" hint :
SELECT TOP 100 id, email, amount
FROM view_orders with (nolock, index=ix_email)
WHERE email LIKE @m
ORDER BY created_at DESC
Not sure it would work though, I don't work at this place anymore.