Login or Sign Up to become a member!
LessThanDot Sit Logo

LessThanDot

Community Wiki

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.

LTD Social Sitings

Lessthandot twitter Lessthandot Linkedin Lessthandot friendfeed Lessthandot facebook Lessthandot rss

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

Navigation

Google Ads

Date Ranges Without Loops

From Wiki

Jump to: navigation, search

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

  1. CREATE TABLE NumberPivot (NumberID INT PRIMARY KEY)
  2.  
  3.     DECLARE @intLoopCounter INT
  4.     SELECT @intLoopCounter =0
  5.  
  6.     WHILE @intLoopCounter <=1000 BEGIN
  7.     INSERT INTO NumberPivot
  8.     VALUES (@intLoopCounter)
  9.  
  10.     SELECT @intLoopCounter = @intLoopCounter +1
  11.     END
  12.     GO


Previous 10 years until today

  1. SELECT DATEADD(yy,-numberID,GETDATE())
  2.     FROM dbo.NumberPivot
  3.     WHERE NumberID < 10


Next 10 years from today

  1. SELECT DATEADD(yy,numberID,GETDATE())
  2.     FROM dbo.NumberPivot
  3.     WHERE NumberID < 10


Next 100 months from today

  1. SELECT DATEADD(mm,numberID,GETDATE())
  2.     FROM dbo.NumberPivot
  3.     WHERE NumberID < 100


Next 100 weeks from 2000-01-01

  1. DECLARE @dtmDate DATETIME
  2.     SELECT @dtmDate = '2000-01-01 00:00:00.000'
  3.     SELECT DATEADD(wk,numberID,@dtmDate)
  4.     FROM dbo.NumberPivot
  5.     WHERE NumberID < 100


Next 100 quarters from today

  1. SELECT DATEADD(qq,numberID,GETDATE())
  2.     FROM dbo.NumberPivot
  3.     WHERE NumberID < 100


Contributed by: --SQLDenis 16:55, 30 May 2008 (GMT)

Part of SQL Server Programming Hacks

Section Dates

123 Rating: 1.8/5 (8 votes cast)