使用动态SQL +变量会加快我的查询速度吗?

时间:2012-11-27 19:06:32

标签: sql-server-2008 tsql variables

我最近意识到,当我在过滤器中引用变量而不是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)

0 个答案:

没有答案