简体   繁体   English

在SQL Server中循环浏览日期范围

[英]Loop through range of dates in SQL Server

I have a stored procedure that looks like : 我有一个看起来像的存储过程:

CREATE procedure [dbo].[SP_EXEC] 
AS
   DECLARE @DATE AS varchar(50)

   SET @DATE = (SELECT TOP(1) CONVERT(VARCHAR, YEAR(DATEADD(MM, DATEDIFF(MM, '01/01/2000', DATEADD(MM, -1, GETDATE())), '01/01/2000'))) + RIGHT('00'+ CONVERT(VARCHAR, MONTH(DATEADD(MM, DATEDIFF(MM, '01/01/2000', DATEADD(MM, -1, GETDATE())), '01/01/2000'))), 2) + RIGHT('00' + CONVERT(VARCHAR, DAY(DATEADD(MM, DATEDIFF(MM, '01/01/2000', DATEADD(MM, -1, GETDATE())), '01/01/2000'))), 2)
                FROM produit)

    EXEC SP_DELETE_lIGNE_MOIS_EN_COURS  @DATE

The stored procedure works fine, my goal is to do a loop of a range of date from 2012/03/01 to the current date. 存储过程工作正常,我的目标是循环执行从2012/03/01到当前日期的日期范围。 How to update my stored procedure to do an update on history ? 如何更新我的存储过程以对历史记录进行更新?

There's really not enough information here to be sure what you need... but first few observations: 实际上,这里没有足够的信息来确保您需要的信息……但是,首先要注意的是:

You have a select top 1 from a table, but you're not selecting anything from it 您从表中选择了前1个,但没有从中选择任何东西

You have quite complex select, which looks like it's the same as this: 您有相当复杂的选择,看起来就像这样:

convert(dateadd(month, DATEDIFF(month, 0, getdate()), 0), 112)

Which is the first day of current month in YYYYMMDD format YYYYMMDD格式的当月第一天

You're assigning that to a varchar(50) -- and passing as a parameter to a procedure. 您正在将其分配给varchar(50),并将其作为参数传递给过程。 Is the procedure actually using a date or datetime for this? 程序实际上为此使用日期还是日期时间?

So, my guess is that you actually need this: 因此,我的猜测是您实际上需要此:

declare @date date

set @date = '20120301'

while (@date < getdate()) begin

    exec SP_DELETE_lIGNE_MOIS_EN_COURS @date

    set @date = dateadd(month, 1, @date)
end 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM