我在使用迭代SQL脚本时遇到了麻烦。
我需要的是计算每个月的文档清单,但我不能迭代where子句,我需要的是使每个EOMONTH(@VarDate, 0)
(从列和where)类似于EOMONTH(@VarDate, n+1)
,它必须在T-SQL中。
我想要得到的结果是从VarDate 2019到今天每个月的下一个。
Expediente | VarDate | 15004/2018 | 2019-01-31 | 500/2019
---|---|
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