SQL Server: Create a Table of Dates

This Sql Server script will create a function that returns all dates in a date range as a table.

CREATE FUNCTION dbo.DateTable (
@StartDate smalldatetime,
@EndDate smalldatetime)
RETURNS @DatesTable TABLE (DateCol smalldatetime)
AS
WHILE @StartDate < = @EndDate BEGIN INSERT INTO @DatesTable (DateCol) VALUES (@StartDate) SET @StartDate = DateAdd(dd,1,@StartDate) END RETURN END GO GRANT SELECT ON dbo.DateTable TO PUBLIC GO

Leave a Reply

Your email address will not be published. Required fields are marked *