开发者

How to retrieve / add records involving date spans in SQL?

开发者 https://www.devze.com 2023-04-01 02:06 出处:网络
I have a table in SQL Server containing a series of weeks by when the week begins: id weekBeginning 12011-08-07 00:00:00

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:

DECLARE @dt DATETIME = '2011-09-15 13:42';

You can run this code:

-- just declare a variable to avoid expressing twice:
DECLARE @mw DATETIME = (SELECT MAX(WeekBeginning) FROM WeekTable);

;WITH n AS
(
       SELECT DISTINCT n = number
               FROM [master]..spt_values
               WHERE number BETWEEN 1 AND DATEDIFF(WEEK, @mw, @dt)
)
INSERT dbo.WeekTable(WeekBeginning)
SELECT DATEADD(WEEK, n, @mw) 
    FROM n ORDER BY n;

No need for a loop, and not sure where you're learning syntax - date_add is not correct and the interval keyword is not valid either.

0

精彩评论

暂无评论...
验证码 换一张
取 消