CTE list of dates on the fly:
WITH D AS
(
SELECT number AS rn FROM master.dbo.spt_values
WHERE type = 'P' AND number BETWEEN 0 AND 29
)
SELECT DATEADD(dd, -D.rn, DATEADD(dd, DATEDIFF(dd,0,GETDATE()), 0)) AS ReportDate
FROM D;
2000/pre CTE solution here
Showing posts with label List of dates. Show all posts
Showing posts with label List of dates. Show all posts
Wednesday, 24 November 2010
Tuesday, 23 November 2010
Create a list of dates on the fly - SQL
I've recently had the requirement to produce a list of the last 30 days on the fly (I didn't have the option to refer to a 'Numbers' table). This was to be used as a 'Command' in Crystal Reports and joined to a database table to produce 'missing dates'.
Using the system table, spt_values, the first stage was to produce a list of numbers:
SELECT number AS rn FROM master.dbo.spt_values
WHERE type = 'P' AND number BETWEEN 0 AND 29
This is then extended to produce a list of the last 30 dates.
SELECT DATEADD(dd, -D.rn, DATEADD(dd, DATEDIFF(dd,0,GETDATE()), 0)) AS ReportDate
FROM (
SELECT number AS rn FROM master.dbo.spt_values
WHERE type = 'P' AND number BETWEEN 0 AND 29
) AS D
This was with help from both Chris Morris & Kevin McKelvey at http://www.sqlservercentral.com/
CTE solution here
Using the system table, spt_values, the first stage was to produce a list of numbers:
SELECT number AS rn FROM master.dbo.spt_values
WHERE type = 'P' AND number BETWEEN 0 AND 29
This is then extended to produce a list of the last 30 dates.
SELECT DATEADD(dd, -D.rn, DATEADD(dd, DATEDIFF(dd,0,GETDATE()), 0)) AS ReportDate
FROM (
SELECT number AS rn FROM master.dbo.spt_values
WHERE type = 'P' AND number BETWEEN 0 AND 29
) AS D
This was with help from both Chris Morris & Kevin McKelvey at http://www.sqlservercentral.com/
CTE solution here
Labels:
Auxiliary,
Crystal Reports,
DateAdd,
DateDiff,
Dates,
GetDate,
List of dates,
Missing Dates,
SQL
Subscribe to:
Posts (Atom)