MSSQL递归日期添加

MSSQL递归日期添加,sql,sql-server,tsql,Sql,Sql Server,Tsql,Hello Iv在一个查询中遇到了很大的问题,下一个日期是从上一个记录中计算出来的 我有一张桌子 create table #t1 ( M_ID int, --ID of group STEP int, -- Step number DateTo Datetime, --DateTo AddDays int) --Number of days to add to NEXT record --测试数据 这张桌子看起来怎么样 逻辑: 我已经筋疲力尽了 常见问题 必须在T-SQL(8KK reco

Hello Iv在一个查询中遇到了很大的问题,下一个日期是从上一个记录中计算出来的

我有一张桌子

create table #t1 (
M_ID int, --ID of group
STEP int, -- Step number
DateTo Datetime, --DateTo
AddDays int) --Number of days to add to NEXT record
--测试数据

这张桌子看起来怎么样

逻辑:

我已经筋疲力尽了

常见问题
必须在T-SQL(8KK records+)中完成,请正确设置问题的格式。非常有用,谢谢,以前尝试过常用表表达式,但没有成功。
INSERT INTO #t1
select 1, 1, GETDATE(), 0 union
select 1, 2, null, 1 union
select 1, 3, null, 0 union
select 1, 4, null, 0 union
select 2, 1, GETDATE(), 0 union
select 2, 2, NULL, 1 union
select 2, 3, NULL, 0 
If step = 1 then DateTo = GETDATE()
At step 2 of M_ID 1 previous row had 0 days to add so it should copy DateTo from previous row
At step 3 of M_ID 1 previous row has 1 day to add to previous DateTo
;with cte as (
    select M_ID, STEP, DateTo, AddDays
    from #t1
    where STEP = 1
    union all
    select t.M_ID, t.STEP, dateadd(dd, c.AddDays, c.DateTo), t.AddDays
    from #t1 t
    inner join cte c on t.M_ID = c.M_ID and t.STEP = c.STEP + 1
)

select *
from cte