当我在查询中间使用字符串作为日期时,我在查询中看到性能下降(速度慢2倍-3x),而不是先将字符串值放入类型为smalldatetime
的变量中。所以例如
declare @rptDate AS smalldatetime
set @rtpDate = CAST('2014-06-22' AS smalldatetime)
SELECT SUM(tons) FROM sales
WHERE ItemClass IN (1, 3, 5, 7)
AND AcctNo LIKE '31_-30[12]0'
AND YEAR(InvDate) = YEAR(@rptDate)
AND MONTH(InvDate) = MONTH(@rptDate) '
AND DAY(InvDate) <= DAY(@rptDate)
肯定比
更快SELECT SUM(tons) FROM sales
WHERE ItemClass IN (1, 3, 5, 7)
AND AcctNo LIKE '31_-30[12]0'
AND YEAR(InvDate) = YEAR('2014-06-22')
AND MONTH(InvDate) = MONTH('2014-06-22')
AND DAY(InvDate) <= DAY('2014-06-22')
那么为什么“正确的优化”不会发生在这里呢?
答案 0 :(得分:0)
我会再往前走了
declare @rptDate AS smalldatetime
declare @year as int
declare @month as int
declare @day as int
set @rtpDate = CAST('2014-06-22' AS smalldatetime)
set @year = year(@rtpDate)
set @month = month(@rtpDate)
set @day = day(@rtpDate)
SELECT SUM(tons) FROM sales
WHERE ItemClass IN (1, 3, 5, 7)
AND AcctNo LIKE '31_-30[12]0'
AND YEAR(InvDate) = @year
AND MONTH(InvDate) = @month
AND DAY(InvDate) <= @day