Skip to main content
nikos101
Inspiring
January 7, 2009
Question

Interesting date query I need some help with

  • January 7, 2009
  • 5 replies
  • 871 views
I need to select dates for each day starting from a particular date up until the present day. These dates are for days where a value doesn't exist in the table.


Thanks for any advice

This topic has been closed for replies.

5 replies

Inspiring
January 8, 2009
The way our "calendar" table works is that the primary key is the date. Other fields include fiscal year, fiscal period, fiscal quarter, holiday, and things like that. There are many foreign key references to this table.

To update it, we have a script that adds a year and updates everything except the holidays. That we do manually with a Cold Fusion web page.

It is relelevent that the software for this db, redbrick, has date, time, and timestamp fields. In other words, a date field does not include the time component.
nikos101
nikos101Author
Inspiring
January 8, 2009
Thanks, I managed to pull off the sql thing cfSearching mentioned. What is the best way to update this calendar table?
Inspiring
January 7, 2009
> how to do this purely in sql

In ms sql you could use a table valued udf. The udf could generate the dates and insert them into a table variable that would be used in your join. The basic logic is the same. Create two variables: @startDate and @todaysDate. Then loop while the start date is <= today's date. Within each loop insert the current date into the table variable, and increment the start date

http://msdn.microsoft.com/en-us/library/ms191165.aspx

while @startDate <= @today
begin
insert into @dateTable (theDate) values (@startDate)

set @startDate = dateAdd(d, 1, @startDate)
end

Though personally I prefer using using a permanent calendar table. I use that table in my selects rather than generating a table of dates each time.

nikos101
nikos101Author
Inspiring
January 7, 2009
Thats pretty clever stuff thanks Dan Bracuk . I would like to test it in the sql server so could someone show me how to do this purely in sql (with arbitary startDate)
Inspiring
January 7, 2009
select date2
from sometables
right join
(<cfset thedate = startdate>
<cfloop condition = "thedate lt now()>
select distinct #thedate# date2
from some_small_table
union
<cfset thedate = dateadd("d", 1, thedate)>
</cfloop>
select distinct #thedate# date2
from some_small_table

) sq on something = date2
where somefield is null