FUNCTION TO GET MONTHS WITH YEAR BETWEEN TWO GIVEN DATES

Pavanandey
Posted by Pavanandey under Sql Server category on | Views : 3801
CREATE FUNCTION [dbo].[getmonths]   
(@StartDate Datetime,@EndDate DateTime)
RETURNS
@Dates TABLE
(
Date varchar(100) ,
Monthval int,
yearval int
)
AS
BEGIN
While @StartDate <= @EndDate
begin
declare @string varchar(100)
set @string = datename(MM,@StartDate) + ' ' + datename(yyyy,@StartDate)
insert @Dates(Date,Monthval,yearval) Values(@string,datepart(MM,@StartDate),datepart(YYYY,@StartDate))
Set @StartDate = DATEADD(month , 1, @StartDate )
end
RETURN
END
------------------------------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------------------------------
declare @FromDate Datetime
declare @ToDate Datetime
set @FromDate = '04/01/2009'
set @ToDate = '03/31/2010'
select * from [getmonths](@FromDate,@ToDate)
------------------------------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------------------------------


THE OUTPUT IS AS BELOW
------------------------------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------------------------------
April 2009
May 2009
June 2009
July 2009
August 2009
September 2009
October 2009
November 2009
December 2009
January 2010
February 2010
March 2010

Comments or Responses

Login to post response