递归Where子句SQL CTE查询



我在使用迭代SQL脚本时遇到了麻烦。

我需要的是计算每个月的文档清单,但我不能迭代where子句,我需要的是使每个EOMONTH(@VarDate, 0)(从列和where)类似于EOMONTH(@VarDate, n+1),它必须在T-SQL中。

我想要得到的结果是从VarDate 2019到今天每个月的下一个。

tbody> <<tr>500/2019669/201916232/201813945/2018
Expediente VarDate
15004/20182019-01-31
2019-01-31
2019-01-31
.......
2022-06-30
2022-06-30

SOLVED ....使用WHILE代替CTE

DECLARE @Inicio date
SET @Inicio = '2019-01-01'
DECLARE @Exp TABLE (Expediente varchar(255), Periodo date)
WHILE EOMONTH(@Inicio,0) <= EOMONTH(GETDATE(),0)
BEGIN
INSERT INTO @Exp
select cast(numexp as nvarchar)+'/'+cast(añoexp as nvarchar) Expediente, EOMONTH(@Inicio,0) Periodo
FROM syn_TControl_Movimientos_expediente m
where m.fase=1 and (m.Fecha <= EOMONTH(@Inicio,0)  AND (m.CveMov IN (1,3))
AND (m.ConsMov =(Select MAX(ConsMov) as Expr1 from syn_TControl_Movimientos_Expediente as m2
WHERE (NumExp=m.NumExp) and (AñoExp = m.AñoExp) and (Fecha <= EOMONTH(@Inicio,0)))))
SET @Inicio = DATEADD(Month,1,@Inicio)
END;
SELECT * FROM @Exp

相关内容

  • 没有找到相关文章

最新更新