Sunday, January 13, 2008

SQL Date Ranges UDF with CTE in TSQL

SQL Date Ranges


CREATE FUNCTION DateRange(@start DATETIME, @end DATETIME)

RETURNS TABLE
AS
RETURN (
WITH DateRange(CurrentDate) AS(
SELECT @start as CurrentDate
union all
SELECT DATEADD(day,1,CurrentDate)
FROM DateRange
WHERE CurrentDate < @end)
SELECT CurrentDate FROM DateRange );
' ------------------------------------------
usage:
SELECT CurrentDate FROM DateRange('20010101','20120901') OPTION(MAXRECURSION 10000)

No comments: