October 2011
M T W T F S S
    Nov »
 12
3456789
10111213141516
17181920212223
24252627282930
31  

Problem with a MTD query

I was running a query today and was not able to SUM by the current month. I checked the code and didn’t see any issues there, but when I looked at the variables it was pretty obvious.

DECLARE @targetdate VARCHAR(8)
DECLARE @previousdate VARCHAR(8)
DECLARE @currentmonth INT
DECLARE @currentday INT

SET @targetdate = CONVERT(VARCHAR(8), GETDATE() – 1, 112)
SET @previousdate = CONVERT(VARCHAR(8), GETDATE() – 2, 112)
SET @currentmonth = ( 10 * CAST(DATEPART(Year, GETDATE() – 1) AS INT) ) + CAST(DATEPART(Month, GETDATE() – 1) AS INT)
SET @currentday = CAST(DATEPART(Day, GETDATE() – 1) AS INT)

Which results in:

20111018
20111017
20120
18

I was setting @currentmonth incorrectly. The correct value is:

SET @currentmonth = ( 100 * CAST(DATEPART(Year, GETDATE() – 1) AS INT) ) + CAST(DATEPART(Month, GETDATE() – 1) AS INT)

Which gives the correct date/month

20111018
20111017
201110
18

Big difference!

Leave a Reply