I have a table in SQL Server containing a series of weeks by when the week begins:
id weekBeginning
1 2011-08-07 00:00:00
2 2011-08-14 00:00:00
3 2011-08-21 00:00:00
4 2011-08-28 00:00:00
I would like a stored proc that, when inputted a date @dt, it outputs the id of the week containing that date, creating a row for that week if one does not exist. There will be no overlap between when weeks begin.)
I have tried the following in SQL Server, but it says I have invalid syntax. What would be the correct way to accomplish this?
declare @weekid int
declare @weekBeginning datetime
while not exists(select @weekid = id from WeekTable where @dt between weekBeginning and date_add(weekBeginning, interval 7 day))
begin
set @weekBeginning = (select max(weekBeginning)) from WeekTable
insert WeekTable(weekBeginning) output inserted.id into @weekid values date_add(@weekBeginning, interval 7 day)
end
Now that I’ve re-read the requirements.
Given an arbitrary date/time in any week after the max week in the table:
You can run this code:
No need for a loop, and not sure where you’re learning syntax –
date_addis not correct and theintervalkeyword is not valid either.