Want to display 12 months name from sql server
This query is to obtain all month names and month no's
SELECT DATENAME(MONTH, DATEADD(MM, s.number, CONVERT(DATETIME, 0))) AS [MonthName],
MONTH(DATEADD(MM, s.number, CONVERT(DATETIME, 0))) AS [MonthNumber]
FROM master.dbo.spt_values s
WHERE [type] = 'P' AND s.number BETWEEN 0 AND 11
ORDER BY 2
The With R(N)
is a Common Table Expression. From MDSN:
A common table expression (CTE) can be thought of as a temporary result set that is defined within the execution scope of a single SELECT, INSERT, UPDATE, DELETE, or CREATE VIEW statement. A CTE is similar to a derived table in that it is not stored as an object and lasts only for the duration of the query. Unlike a derived table, a CTE can be self-referencing and can be referenced multiple times in the same query.
The R
is the name of the result set (or table) that you are generating. And the N
is the month
number.
This CTE in particular is a Recursive Common Table Expression. From MSDN:
A common table expression (CTE) provides the significant advantage of being able to reference itself, thereby creating a recursive CTE. A recursive CTE is one in which an initial CTE is repeatedly executed to return subsets of data until the complete result set is obtained.
When using CTE my suggestion would to be more descriptive with the names. So for your example you could use the following:
;WITH months(MonthNumber) AS
(
SELECT 0
UNION ALL
SELECT MonthNumber+1
FROM months
WHERE MonthNumber < 12
)
select *
from months;
In my version the months
is the name of the result set that you are producing and the monthnumber
is the value. This produces a list of the Month Numbers from 0-12 (See Demo).
Result:
| MONTHNUMBER |
---------------
| 0 |
| 1 |
| 2 |
| 3 |
| 4 |
| 5 |
| 6 |
| 7 |
| 8 |
| 9 |
| 10 |
| 11 |
| 12 |
Then the SELECT
statement immediately after is using the values of the CTE result set to get you the Month Names.
Final query (See Demo):
;WITH months(MonthNumber) AS
(
SELECT 0
UNION ALL
SELECT MonthNumber+1
FROM months
WHERE MonthNumber < 12
)
SELECT LEFT(DATENAME(MONTH,DATEADD(MONTH,-MonthNumber,GETDATE())),3) AS [month]
FROM months;