Search This Blog

Friday 5 June 2015

Get Months Within a Date Range With SQL Query Or Get Months Within a Financial Year Date Range With SQL Query

DECLARE @StartDate DATETIME = '2015-04-01'
DECLARE @EndDate DATETIME = '2016-03-31'

Step 1:- Using Query

SELECT  DATENAME(MONTH, DATEADD(MONTH, x.number, @StartDate)) + ' ' + DATENAME(YEAR,  DATEADD(MONTH, x.number, @StartDate)) 'Month'
FROM    master.dbo.spt_values x
WHERE   x.type = 'P'       
AND     x.number <= DATEDIFF(MONTH, @StartDate, @EndDate);


Step 2:- Using CTE Query

WITH CTE AS
(
    SELECT CAST(@StartDate AS DATE) AS Start_Date
    UNION ALL
    SELECT DATEADD(MONTH, 1, Start_Date)
    FROM CTE
    WHERE DATEADD(MONTH, 1, Start_Date) <= CAST(@EndDate AS DATE)  
)
SELECT  DATENAME(MONTH, Start_Date) + ' ' + DATENAME(YEAR, Start_Date) 'Month'
FROM CTE




No comments:

Post a Comment