我最近意识到,当我在过滤器中引用变量而不是 SQL Server 2008 中的实际值时,查询会慢得多。例如:
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'
比
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
将我的查询更改为此会使查询与我发布的第一个查询一样快:
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)