Problem
I was wondering if I could get the month names in order by writing a simple SQL statement. The same SQL statement should also be reusable for other projects. I had a SQL Server Reporting Services (SSRS), and I needed to create a report to show the monthly status of the stock list in my company. There were two parameters I need to pass to view the report.
- Month
- Year.
The year parameter should list the years from the first date in the table to current year. The month parameter should list all the months in a year, and the report should display the months ordered as shown below.
The report should display the data based on the month parameter and year parameter. For example, if you select the month ‘January’ and Year ‘2011’ the report should display only the data based on the selection.
Solution
There are different ways to get the month names in order; it depends upon how you think and what you think. First, I thought using the static way, like creating a table variable and inserting the values 1, 2, 3, 4…12 into the table variable and then selecting the month names. Next, I thought by giving the two dates and pulling the months between the two dates (pulling the month names between 01-Jan-1900 to 01-Dec-1900). The important thing is ordering the months. When you sort the month names, they are usually ordered based on the name alphabetically, as shown below.
Both the queries I have written for these scenarios need to use a row-based approach (row by row). I googled to see if there any other ways to get the results by writing simple statements by keeping performance and re-usability in my mind, but I had no luck.
At last I found a way to write a query using a recursive common table expression (CTE). This in-line query will pull the month numbers by adding the month number + 1 recursively upto 12. Then it converts the month number to the month name by using the datename function explicitly.
The result of the above query:
I suggest you create this query as a view to use it for any other SQL scripts in joins. You can also create it as a stored procedure to use in a report. If the requirement from your client is to include only the first three characters for the month in CAPS, then you just alter the stored procedure for the requirement and use SUBSTRING or LEFT and UPPER function to return these values.