I've realized lately that queries are much slower when I reference a variable in the filter instead of the actual value in SQL Server 2008. For example:
SELECT table_A.fruit
, SUM(table_B.units)
FROM table_A LEFT JOIN table_B
ON table_A.fruit = table_B.fruit_name
WHERE time_of_sale BETWEEN '2012-11-01' AND '2012-11-25'
is faster than
DECLARE @date1 DATE = '2012-11-01'
, @date2 DATE = '2012-11-25'
SELECT table_A.fruit
, SUM(table_B.units)
FROM table_A LEFT JOIN table_B
ON table_A.fruit = table_B.fruit_name
WHERE time_of_sale BETWEEN @date1 AND @date2
Would changing my query to this make the query as fast as the first one I posted:
DECLARE @date1 DATE = '2012-11-01'
, @date2 DATE = '2012-11-25'
DECLARE @exec VARCHAR(8000)
SELECT @exec =
'
SELECT table_A.fruit
, SUM(table_B.units)
FROM table_A LEFT JOIN table_B
ON table_A.fruit = table_B.fruit_name
WHERE time_of_sale BETWEEN ''' + @date1 + ''' AND ''' + @date2 + '''
'
EXEC(@exec)