Thursday, July 9, 2020
SQL - table-valued function to get all months between two date range
CREATE FUNCTION [dbo].[GetMonths](@StartDate DATETIME, @EndDate DATETIME)
RETURNS @MonthList TABLE(MonthValue VARCHAR(15) NOT NULL)
AS
BEGIN
--Variable used to hold each new date value
DECLARE @DateValue DATETIME
--Start with the starting date in the range
SET @DateValue=@StartDate
--Load output table with the month part of each new date
WHILE @DateValue <= @EndDate
BEGIN
INSERT INTO @MonthList(MonthValue)
SELECT cast(@DateValue as date)
--Move to the next month
SET @DateValue=DATEADD(mm,1,@DateValue)
END
RETURN
END
Labels:
SQL
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment