如何在 while 中使用 DateAdd

how to use DateAdd in while

我创建了一个函数来获取接下来四个日期 weeks.For 执行此操作我使用下面的代码。但我不遵守并收到错误。

    create function GetNextDays()
returns @somedays table
(

dayDate date
)
as
begin
declare @today date=getdate()
declare @index int=0
while @index<3
    begin
    insert @somedays(dayDate) values(@today)
    set @index=@index+1;
     DATEADD(DD,7,CAST(@today AS DATE))
    end
return
end

我收到这个错误:

Incorrect syntax near 'DATEADD'.

您应该在 DateADD 之前使用 set。见下面的代码:

   alter function GetNextDays()
returns @somedays table
(

dayDate date
)
as
begin
declare @today date=getdate()
declare @index int=0
while @index<3
    begin
    insert @somedays(dayDate) values(@today)
    set @index=@index+1;
    set @today= DATEADD(DD,7,cast(@today as date))
    end
return
end

更改此行:

DATEADD(DD,7,CAST(@today AS DATE))

与 :

set @today= DATEADD(DD,7,cast(@today as date))

你根本不应该为此使用循环。您应该使用数字或计数 table。我把这个放在 cte 里给你看。我在我的系统上有一个视图,我可以在不需要循环的情况下使用这种类型的东西。

WITH
    E1(N) AS (select 1 from (values (1),(1),(1),(1),(1),(1),(1),(1),(1),(1))dt(n)),
    E2(N) AS (SELECT 1 FROM E1 a, E1 b), --10E+2 or 100 rows
    E4(N) AS (SELECT 1 FROM E2 a, E2 b), --10E+4 or 10,000 rows max
    cteTally(N) AS 
    (
        SELECT  ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) FROM E4
    )

select DATEADD(day, N, cast(getdate() as DATE))
from cteTally
where N <= 3