Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. How to update my stored procedure to do an update on history ?


1 Answers

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

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

You're assigning that to a varchar(50) -- and passing as a parameter to a procedure. 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 
like image 175
James Z Avatar answered Oct 30 '25 06:10

James Z