I want to display 12 months name from sql server. i though to accomplish insert month name into temp table and then fire select statement on that table. so i had to write 12 insert table to insert 12 months name. so i search google to find better solution and i got it.
here is the sql statement
WITH R(N) AS
(
SELECT 0
UNION ALL
SELECT N+1
FROM R
WHERE N < 12
)
SELECT LEFT(DATENAME(MONTH,DATEADD(MONTH,-N,GETDATE())),3) AS [month]
FROM R
the above script works perfectly but my problem is i just do not understand how it works. i never work with CTE.
so tell me what is the meaning of WITH R(N) AS
and see this sql
SELECT LEFT(DATENAME(MONTH,DATEADD(MONTH,-N,GETDATE())),3) AS [month] FROM R
when above sql execute how it is getting value for -N ??
because here i have not set anything for -N ??
so please anyone help me to understand how whole thing works. thaks
My Second Phase of Question
just have look a and tell me
;WITH months(MonthNumber) AS
(
SELECT 0
UNION ALL
SELECT MonthNumber+1
FROM months
WHERE MonthNumber < 12
)
onething is not clear to me that why only first time the below part execute
SELECT 0
UNION ALL
SELECT MonthNumber+1
FROM months
WHERE MonthNumber < 12
and from the 2nd time only this below part execute
SELECT MonthNumber+1
FROM months
WHERE MonthNumber < 12
whenever we write two sql statement using Union and execute then always it return data from two sql state but specially in this case from the 2nd time why only this below part
execute
SELECT MonthNumber+1
FROM months
WHERE MonthNumber < 12
basically i not familiar with CTE with recursion technique and that is why things is not getting clear to me. if possible please discuss how CTE recursion works.
DECLARE @TotaDays SMALLINT
DECLARE @Month VARCHAR(15)
DECLARE @Year SMALLINT
DECLARE @date DATETIME
SET @Month = 'January'
SET @Year = 2015
SET @date = '01 ' + @Month + ' ' + CONVERT(VARCHAR(4),@Year)
SET @TotaDays = 0
SELECT @TotaDays = DATEDIFF(DAY, @date, DATEADD(MONTH, 1, @date))
;WITH months(MonthNumber) AS
(
SELECT 1
UNION ALL
SELECT MonthNumber+1
FROM months
WHERE MonthNumber < @TotaDays
)
select * from months;
The
With R(N)is a Common Table Expression. From MDSN:The
Ris the name of the result set (or table) that you are generating. And theNis themonthnumber.This CTE in particular is a Recursive Common Table Expression. From MSDN:
When using CTE my suggestion would to be more descriptive with the names. So for your example you could use the following:
In my version the
monthsis the name of the result set that you are producing and themonthnumberis the value. This produces a list of the Month Numbers from 0-12 (See Demo).Result:
Then the
SELECTstatement immediately after is using the values of the CTE result set to get you the Month Names.Final query (See Demo):