Click here to Skip to main content
15,885,767 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am passing Month and Year as Parameters to the Query.
I need Last twelve trailing months based on month and year.

For Eg:
I am giving January , 2016 as parameter.
I want to get the column names as

Jan-15,Feb-15,Mar-15,Apr-15,,,,,,,,,,,Dec-15
Posted
Updated 14-Jan-16 1:56am
v3
Comments
ZurdoDev 14-Jan-16 7:31am    
You'll need to probably dump last twelve months into a temp table using the date passed in and then pivot it and format the columns appropriately.

Where are you stuck?

As said in solution 1 this can be done in different ways. However, if possible I would avoid using dynamic column names. Very often using dynamic names introduces other problems and complexity when the result set is used. Depending on the situation the order of the columns may change or the calling side is unaware of the formatted names and so on.

So if possible, I'd provide the data to the calling side (a separate query, a header row in the result set etc.) and use fixed column names and do the possible renaming on the client side based on the known names for each column.
 
Share this answer
 
There are two ways. Using the PIVOT command or using dynamic SQL and sp_ExecuteSQL.

If you use dynamic SQL make sure you pass all your parameters into it's execution as parameters to negate SQL injection vulnerabilities.

Someone has answered almost this exact question using the dynamic SQL method here:

How to get Dynamic Column names in SELECT statement[^]

For help using the PIVOT see the following:

sql - PIVOT with MONTH() - Stack Overflow[^]
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900