I have a SQL 2008 R2 database with approximately 2 million rows in one of the tables, and I am struggling with the performance of a particular query when using parameterized SQL.
The table has a field containing the name in it:
[PatientsName] nvarchar NULL,
The field also has a simple index:
CREATE NONCLUSTERED INDEX [IX_Study_PatientsName] ON [dbo].[Study] ( [PatientsName] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [INDEXES] GO
When I make this request in the management studio, it takes about 4 seconds to complete:
declare @StudyPatientsName nvarchar(64) set @StudyPatientsName= '%Jones%' SELECT COUNT(*) FROM Study WHERE Study.PatientsName like @StudyPatientsName
declare @StudyPatientsName nvarchar(64) set @StudyPatientsName= '%Jones%' SELECT COUNT(*) FROM Study WHERE Study.PatientsName like @StudyPatientsName
But, when I execute this request:
SELECT COUNT(*) FROM Study WHERE Study.PatientsName like '%Jones%'
SELECT COUNT(*) FROM Study WHERE Study.PatientsName like '%Jones%'
it takes more than one and a half seconds to complete.
Considering execution plans, a query without parameterization performs an index scan using the aforementioned index, which is obviously effective. A parameterized query uses an index, but whether the range is executed by index.
Part of the problem is with the main template. When I delete the main template, both queries return for a split second. Unfortunately, I need to support leading wildcards.
We have a home ORM that sets up parameterized queries that have a problem. These queries are executed based on user input, so parameterized queries make sense to avoid things like SQL injection attack. I am wondering if there is a way to make a parameterized query function, as well as a non-parameterized query?
I did some research, considering various ways to give hints to the query optimizer, trying to get the optimizer to repeat the query plan for each query, but have not yet found anything to improve performance. I tried this query:
SELECT COUNT(*) FROM Study WHERE Study.PatientsName like @StudyPatientsName OPTION ( OPTIMIZE FOR (@StudyPatientsName = '%Jones%'))
which was mentioned as a solution in this matter, but it did not matter.
Any help would be appreciated.