Thursday 19 December 2013

Get Months between two dates

Select top 12* FROM fn_getMonth(1)




-- Author: Nitish Jha -> 19 Dec 13.
-- If 0 Then Jan, Feb etc Else 1 to 12. 
Create function fn_getMonth (@DispType tinyint)     
Returns @Months Table (Months varchar(20))     
Begin     
DECLARE @startdt DATETIME, @enddt DATETIME     
Set @startdt =  (Select top 1 ActualStartDate from sessionmaster Where isDefault='Yes')     
Set @enddt =  (Select top 1 ActualEndDate from sessionmaster Where isDefault='Yes')     
    if (@DispType=0)   BEGIN
INSERT INTO @Months VALUES (Left(DateName(mm,@startdt),3))     
--INSERT INTO @Months VALUES (Month(@startdt))   
   
WHILE @startdt < @enddt     
BEGIN     
 SET  @startdt = DATEADD(MONTH,1,@startdt)     
 INSERT INTO @Months VALUES (Left(DateName(mm,@startdt),3))     
  --INSERT INTO @Months VALUES (Month(@startdt))   
END 
END
ELSE
BEGIN
INSERT INTO @Months VALUES (Month(@startdt))   
   
WHILE @startdt < @enddt     
BEGIN     
 SET  @startdt = DATEADD(MONTH,1,@startdt)     
  INSERT INTO @Months VALUES (Month(@startdt))   
END 
END
   
Return     
End



Cheers!!!

No comments:

Post a Comment