I have written the below VIEW using a UDF, but am wondering if there is a way to do this without needing a UDF. The only other option I could find is to SELECT UNION hardcoded values, but I don’t like that. Any suggestions or should I just leave it as it is? I am using MS SQL Server 2008 R2, so anything available there is free game.
CREATE FUNCTION GetN(@N int)
RETURNS @numbers TABLE (N int PRIMARY KEY NOT NULL)
AS
BEGIN
DECLARE @i int
SET @i = 0
WHILE (@i < @N)
BEGIN
INSERT @numbers SELECT @i
SET @i = @i + 1
END
RETURN
END
GO
CREATE VIEW Last10Weeks AS
SELECT DATEPART(wk, GETDATE())-N as WeekNumber
, DATEADD(day, (N*-7) - 1 - (DATEPART(dw, GETDATE()) + @@DATEFIRST - 2) % 7, GETDATE()) AS StartDate
, DATEADD(day, (N*-7) + 5 - (DATEPART(dw, GETDATE()) + @@DATEFIRST - 2) % 7, GETDATE()) AS EndDate
FROM GetN(10)
Here’s a way using a recursive CTE:
The “count” is specified by the “N < 10” part at the end of the second SELECT.
Prints out: