snippetsqlMinor
How to generate list of dates --- ie every day for the past 2 years?
Viewed 0 times
thedateseverypastgenerateforhowlistyearsday
Problem
We're using a business intelligence system and need to load a list of dates so we can flag them as 'last week' or 'last 12 months' or some dynamic value.
I'm wondering what's the simplest way to virtually generate a table that simply lists dates in one column, literally every date from '2014-01-01' to the current date (the other columns I can use a formula from there). Actually even appending future dates on for a year would probably be useful as well.
Now yes I can grab distinct dates from another random fact table that has thousands of entries, but that seems sloppy and is creating a dependency where there really shouldn't be one.
I'm wondering what's the simplest way to virtually generate a table that simply lists dates in one column, literally every date from '2014-01-01' to the current date (the other columns I can use a formula from there). Actually even appending future dates on for a year would probably be useful as well.
Now yes I can grab distinct dates from another random fact table that has thousands of entries, but that seems sloppy and is creating a dependency where there really shouldn't be one.
Solution
Using pure T-SQL, you can do the following:
Or, I also wrote a SQLCLR function to make this a little easier, which is available in the Free version of the SQL# library:
If you want the ending date to be in the future, just replace the
;WITH cte AS
(
SELECT ROW_NUMBER() OVER (ORDER BY (SELECT 1)) - 1 AS [Incrementor]
FROM [master].[sys].[columns] sc1
CROSS JOIN [master].[sys].[columns] sc2
)
SELECT DATEADD(DAY, cte.[Incrementor], '2014-01-01')
FROM cte
WHERE DATEADD(DAY, cte.[Incrementor], '2014-01-01') < GETDATE();Or, I also wrote a SQLCLR function to make this a little easier, which is available in the Free version of the SQL# library:
SELECT [DatetimeVal]
FROM [SQL#].[Util_GenerateDateTimeRange]('2014-01-01', GETDATE(), 1, N'day');If you want the ending date to be in the future, just replace the
GETDATE() in either query.Code Snippets
;WITH cte AS
(
SELECT ROW_NUMBER() OVER (ORDER BY (SELECT 1)) - 1 AS [Incrementor]
FROM [master].[sys].[columns] sc1
CROSS JOIN [master].[sys].[columns] sc2
)
SELECT DATEADD(DAY, cte.[Incrementor], '2014-01-01')
FROM cte
WHERE DATEADD(DAY, cte.[Incrementor], '2014-01-01') < GETDATE();SELECT [DatetimeVal]
FROM [SQL#].[Util_GenerateDateTimeRange]('2014-01-01', GETDATE(), 1, N'day');Context
StackExchange Database Administrators Q#144700, answer score: 6
Revisions (0)
No revisions yet.