SQL Server – Dynamically Get Last X Months and Format Output

sql serversql-server-2008

Using today's

date, I need to be able to go back x months and output in the format of YYYY_MM

At the moment, I am using:

select 
right('0000' + cast(datepart(year, getdate()) as varchar(4)), 4)
+ '_'
+ right('00' + cast(datepart(month, DATEADD(month, -3, GETDATE())) as varchar(2)), 2)

Which will give me a output of:

2015_08

The issue I am having is that if I were to go back 12 months using:

select 
right('0000' + cast(datepart(year, getdate()) as varchar(4)), 4)
+ '_'
+ right('00' + cast(datepart(month, DATEADD(month, -12, GETDATE())) as varchar(2)), 2)

The output would still be:

2015_11 (notice the year is still the same)

I am using SQL 2008

EDIT: Solution

DECLARE @table12 AS varchar(50)
SET @table12 = 'SMD_' + replace(convert(varchar(7),DATEADD(MONTH, -12, GETDATE()),102), '.', '_') 

Best Answer

Well, Aaron's answer is much more thorough than my code snippet.

DECLARE @MonthsBack INT;
SET @MonthsBack = 11;
SELECT REPLACE(CONVERT(VARCHAR(7), 
   DATEADD(MONTH,(-1 * @MonthsBack), GETDATE()), 120),'-','_');

Learn to use the DATE functions such as DATEADD() to move through time. Also, CONVERT gives you options in how you format dates to match the current purpose. (Which could include formatting for other languages.)

Then, if needed, the predefined formats can be further manipulate as needed. Though formatting for printing is best done in the presentation layer.