-1

I am seeing a performance hit (2x-3x slower) in a query when I use strings for a date in the middle of a query, as opposed to putting the string value into a variable of type smalldatetime first. So e.g.

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)

is definitely faster than

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')

So why is "the proper optimization" not happening here?

2
  • Have you tried making three separate vars for @month, @day, and @year? Jul 2, 2014 at 21:57
  • If needs to parse the string to date every row. And it may kill use of indexes.
    – paparazzo
    Jul 2, 2014 at 22:25

1 Answer 1

0

I would go one further

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
2
  • I realize this can be optimized. What I'm really looking for is why can't SQL Server do this optimization on its own. It seems like this is an obvious case where it should. Is there something inherent to T-SQL or SQL Server that I'm missing why it can't?
    – Conrad
    Jul 3, 2014 at 1:36
  • I'm really trying to understand the inner workings of SQL Server here. I actually need to put this in a view, so it's not an option to create variables in this case.
    – Conrad
    Jul 3, 2014 at 1:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.