in

vbCity Blogs

New (temp) place for vbCity Blogs

Mike McIntyre's .NET Journal

Welcome 2009! Create a Calendar with Microsoft Transact SQL (How to iterate days in a series)

One puzzle SQL developers face from time to time is creating a calendar containing a series of days.

Below is some SQL code that will create an in-memory calendar for every day from a begin date to an end date.

By adding more columns to the #Calendar table you could store more information about each day, store hours and pay rate to do pay calculations, or other data you need to capture and process in a series of days.

The example creates a calendar for 2009.  Happy New Year!

Example

DROP TABLE #Calendar

CREATE TABLE #Calendar

(

CalendarDate DATETIME

)

 

DECLARE @StartDate DATETIME

DECLARE @EndDate DATETIME

SET @StartDate = '1/1/2009'

SET @EndDate = '12/31/2009'

 

WHILE @StartDate <= @EndDate

      BEGIN

             INSERT INTO #Calendar

             (

                   CalendarDate

             )

             SELECT

                   @StartDate

 

             SET @StartDate = DATEADD(dd, 1, @StartDate)

      END

 

-- See the results

SELECT * FROM #Calendar

 

 

Only published comments... Dec 31 2008, 03:35 PM by Mike McIntyre
Filed under: , ,

About Mike McIntyre

I  am a programmer, developer, and system architect with 29+years experience including state-of-the-art application development frameworks and languages including Visual Studio versions 2002-2010, .NET Framework versions 1-4, C#, and Visual Basic.

I am a mentor, trainer, and coach in the Microsoft .NET technical community. DevCity is my favorite community site. You can find examples of my involvement with DevCity in the site articles, newsletter articles, and my posts in the forum.

Since 2002 I have hosted a .NET site at http://www.getdotnetcode.com, a place with free and inexpensive Visual Basic and C# source code that can be purchased on an 'as needed' basis.

In 2007 I established a .NET search engine, 'Resources for .NET Developers' at http://dot-net-resources-swicki.eurekster.com

Copyright 1998-2009 vbCity.com LLC
Powered by Community Server (Non-Commercial Edition), by Telligent Systems