I have quite tough task for me to do in T-SQL (MSSQL 2005). I have a table like this:
WeekDay| SlotTime
------------------
| 1 | 07:00
| 3 | 09:00
| 7 | 14:00
| 1 | 15:00
| 4 | 22:00
| 6 | 08:00
where 1st column is WeekDay number and 2nd column is some Time value.
As parameters for my query I have 2 dates, for example:
StartDate = '2011-07-20'
EndDate = '2011-08-17'
This is a range definition for my data. I have to generate for these range all dates where WeekDay (from table above) happens and add to them SlotTime value. So for example, for above dates range result column should be:
2011-07-20 9:00
2011-07-21 22:00
2011-07-23 8:00
2011-07-24 14:00
2011-07-25 7:00
2011-07-25 15:00
2011-07-27 9:00
2011-07-28 22:00
2011-07-30 8:00
etc.
...
Any idea how to achieve this? Any tips? :) I'm considering this quite impossible without some huge(?) calculations and additional tables...
Edit (maybe this snippet will help) I was playing with this function to use it as part of my calculations but was unable to achieve my goal. Maybe some part of this can be used in final solution...
create function dbo.NthWeekDay(
@first datetime, -- First of the month of interest (no time part)
@nth tinyint, -- Which of them - 1st, 2nd, etc.
@dow tinyint -- Day of week we want
) returns datetime as begin
-- Note: Returns a date in a later month if @nth is too large
declare @result datetime
set @result = @first + 7*(@nth-1)
return @result + (7 + @dow - datepart(weekday,@result))%7
end
go
SET DATEFORMAT ymd
SET DATEFIRST 1
select dbo.NthWeekDay('2011-07-20',1,1) as D
go
drop function NthWeekDay