Less Than Dot is a community of passionate IT professionals and enthusiasts dedicated to sharing technical knowledge, experience, and assistance. Inside you will find reference materials, interesting technical discussions, and expert tips and commentary. Once you register for an account you will have immediate access to the forums and all past articles and commentaries.
Date Ranges Without Loops
From Wiki
The trick to havinge date ranges without loops is to use a number table. How does this work? Run the code below and you will see, only create the pivot table once and run all the other code separately.
Create our Pivot table ** do this only once populate it with 1000 rows
- CREATE TABLE NumberPivot (NumberID INT PRIMARY KEY)
- DECLARE @intLoopCounter INT
- SELECT @intLoopCounter =0
- WHILE @intLoopCounter <=1000 BEGIN
- INSERT INTO NumberPivot
- VALUES (@intLoopCounter)
- SELECT @intLoopCounter = @intLoopCounter +1
- END
- GO
Previous 10 years until today
- SELECT DATEADD(yy,-numberID,GETDATE())
- FROM dbo.NumberPivot
- WHERE NumberID < 10
Next 10 years from today
- SELECT DATEADD(yy,numberID,GETDATE())
- FROM dbo.NumberPivot
- WHERE NumberID < 10
Next 100 months from today
- SELECT DATEADD(mm,numberID,GETDATE())
- FROM dbo.NumberPivot
- WHERE NumberID < 100
Next 100 weeks from 2000-01-01
- DECLARE @dtmDate DATETIME
- SELECT @dtmDate = '2000-01-01 00:00:00.000'
- SELECT DATEADD(wk,numberID,@dtmDate)
- FROM dbo.NumberPivot
- WHERE NumberID < 100
Next 100 quarters from today
- SELECT DATEADD(qq,numberID,GETDATE())
- FROM dbo.NumberPivot
- WHERE NumberID < 100
Contributed by: --SQLDenis 16:55, 30 May 2008 (GMT)
Part of SQL Server Programming Hacks
Section Dates



LTD Social Sitings
Note: Watch for social icons on posts by your favorite authors to follow their postings on these and other social sites.