I’m in SQL Server 2008 and I have been working on making some older code use parameters instead of building the queries using string concatenation. And I’m also working on making things work faster by doing things like adding indexes to tables.
The table I am working with has many columns (it’s the heart of a star schema reporting database) and has more than 4M rows. The create for the table looks like:
CREATE TABLE [dbo].[rptTransaction](
...
[Date] [nvarchar](10) NULL,
...
) ON [PRIMARY]
Yes, the date column is poorly named because it collides with a keyword. They are using string dates [remember it’s a reporting database].
When I execute the following code in MS SQL Server Management Studio:
DECLARE @testDate NVARCHAR = N'2012/03/01';
SELECT COUNT(*)
FROM rptTransaction AS t
WHERE t.Date >= @testDate
AND t.Date <= @testDate
OPTION (RECOMPILE);
GO
The results are as follows:
(No column name)
0
On the other hand when I execute the following code:
DECLARE @testDate NVARCHAR = N'2012/03/01';
SELECT COUNT(*)
FROM rptTransaction AS t
WHERE t.Date >= N'2012/03/01'
AND t.Date <= N'2012/03/01'
OPTION (RECOMPILE);
GO
The result is the following:
(No column name)
124888
(I am using the OPTION (RECOMPILE) because otherwise the parametrized version does a full table scan, which takes a long time.)
Run this code:
One my system, the output was just
2.Try this instead:
Much better:
That’s one of two unexpected parts of your query. The other is that you required your value be both >= and <=. In other words, the only way to satisfy the query is if the parameter matched your stored data exactly.
2is never going to do that if the column is all valid dates.