Showing posts with label sql server table with dates.. Show all posts
Showing posts with label sql server table with dates.. Show all posts

Wednesday, January 4, 2012

How to create a list of dates in a table - SQL SERVER

Many time we need a table with all the dates listed in it to confront with some other table which has missing dates. here is the simple method - SQL SERVER
DECLARE @myTable TABLE ( TheDate datetime )

declare @StartDate datetime

declare @Days int

declare @CurrentDay int

set @StartDate = '1/1/2006'

set @Days = 10

set @CurrentDay = 0

while @CurrentDay < @Days

begin

insert @myTable (TheDate) values (dateadd(dd, @CurrentDay, @StartDate))

set @CurrentDay = @CurrentDay + 1

end

select * from @myTable