Friday, March 29, 2013

Get Months between two Dates Sql

Use the Below Functions for Get months between two dates

Create Function  [dbo].[fnNumtoDate]
(
@StartDate  DATETIME,
        @EndDate    DATETIME
)
RETURNS @MonthTable TABLE (
   Mon varchar(20)
)
As
Begin
;WITH MONTHS (date)
AS
(
    SELECT @StartDate
    UNION ALL
    SELECT DATEADD(MONTH,1,date)
    FROM MONTHS
    WHERE DATEADD(MONTH,1,date)<=@EndDate
)

Insert into @MonthTable (Mon)
SELECT  ( CASE MONTH(date)
            WHEN 1 THEN  'January'
            WHEN 2 THEN 'February'
            WHEN 3 THEN 'March' 
            WHEN 4 THEN 'April'
            WHEN 5 THEN 'May'
            WHEN 6 THEN 'June'
            WHEN 7 THEN  'July'
            WHEN 8 THEN 'August'
            WHEN  9 THEN 'September'
            WHEN 10 THEN 'October'
            WHEN 11 THEN 'November'
            WHEN 12 THEN 'December'
          END ) AS MONTH FROM MONTHS
RETURN;
ENd

Select * from dbo.fnNumtoDate( '2012-03-12',GETDATE())