So I have a stored procedure that is working except for how it calculates a certain field. On the tables worked with is a field called DeliveryYearMonth that is simply YYYYMM in its format. I try to compare current month info to previous month info, thus I created the following two variables.
DECLARE @CURDate VARCHAR(50) -- Current time (YYYYMM)
DECLARE @MAGDate VARCHAR(50) -- YearAgo Time (YYYYMM)
SET @CURDate = cast((select max(DeliveryYearMonth) from dbo.datatable) as varchar)
SET @MAGDate = cast((substring(@CURDate,1,4)) as varchar) --For current year
+ cast((substring(@CURDate,5,2) - 1) as varchar) -- To get previous month
This is all fine and dandy unless the the month is January, and thus the month would become 00, and the year would stay the same.
So I tried my hand at an if statement to clear this up.
if(substring(@MAGDate,5,2)) = '00'-- If current Month is January
begin
Set @MAGDate = cast((substring(@CURDate,1,4) - 1) as varchar) --For previous year
+ '12' -- December
end
This always breaks the Month Ago Date (@MAGDate) even if the IF statement isn’t true. I cannot figure out why.
Thanks
To get the previous version of your string, you can do the following:
As a comment suggested, though, you should really just store this as a date, assuming you are using SQL Server 2008 or more recent.