I do a small amount of programming/coding in SQL Server (mostly 2005). I have a table of scheduled events and would like to create a query/view of Jan 1 to Jan 31. I need a date to appear even if there are no events scheduled on that date (using a LEFT JOIN).
There seem to be several alternatives for generating all dates:
- permanent table of every possible date
- permanent table of integers and use DateAdd()
- temporary table
- function that returns a table
I have looked at these faqs that offer similar functionality:
faq183-840 Creates a temporary table
faq183-1100 table variable
faq183-5075 function returning table
This is what I came up with but I would like some feedback. I don't think the usage of any of these alternatives would cause performance issues on the SQL Server.
This function returns a table of date/time periods from a start date/time for X number of periods. The interval is set with strInterval so the function can be used to generate years, quarters, months, weeks, days, hours, minutes, and seconds.
Duane
Hook'D on Access
MS Access MVP
There seem to be several alternatives for generating all dates:
- permanent table of every possible date
- permanent table of integers and use DateAdd()
- temporary table
- function that returns a table
I have looked at these faqs that offer similar functionality:
faq183-840 Creates a temporary table
faq183-1100 table variable
faq183-5075 function returning table
This is what I came up with but I would like some feedback. I don't think the usage of any of these alternatives would cause performance issues on the SQL Server.
This function returns a table of date/time periods from a start date/time for X number of periods. The interval is set with strInterval so the function can be used to generate years, quarters, months, weeks, days, hours, minutes, and seconds.
Code:
CREATE FUNCTION [dbo].[AllDates]
( @datStart Datetime,
@intPeriods int,
@strInterval Char(1)
)
RETURNS @tDates table
(
DT DateTime
)
AS
Begin
Declare @intI int
Declare @datNew DateTime
Set @intI = 0
While @intI < @intPeriods
Begin
Set @datnew =
CASE @strInterval
WHEN 'd' THEN DateAdd(dd, @intI, @datStart)
WHEN 'w' THEN DateAdd(ww, @intI, @datStart)
WHEN 'm' THEN DateAdd(mm, @intI, @datStart)
WHEN 'y' THEN DateAdd(yy, @intI, @datStart)
WHEN 'q' THEN DateAdd(qq, @intI, @datStart)
WHEN 'h' THEN DateAdd(hh, @intI, @datStart)
WHEN 'n' THEN DateAdd(n, @intI, @datStart)
WHEN 's' THEN DateAdd(ss, @intI, @datStart)
END
INSERT INTO @tDates (DT) VALUES (@datNew)
Set @intI = @intI + 1
End
Return
End
Duane
Hook'D on Access
MS Access MVP