Transact-SQL: Esempio di ciclo WHILE su DATETIME utilizzando DATEADD

In questo esempio, utilizzando la funzione DATEADD, viene eseguita una azione per ognuno degli ultimi 7 giorni:

DECLARE @DATATMP AS DATETIME

SET @DATATMP = DATEADD(DAY, -7, GETDATE())

WHILE @DATATMP <= GETDATE()
BEGIN
-- ...
-- ...
-- ...
-- Incrementa la data
SET @DATATMP = DATEADD(DAY,1,@DATATMP)
END

In quest’altro vengono considerati gli ultimi 9 mesi:

DECLARE @DATATMP AS DATETIME

SET @DATATMP = DATEADD(MONTH, -9, GETDATE())

WHILE @DATATMP <= GETDATE()
BEGIN
-- ...
-- ...
-- ...
-- Incrementa la data
SET @DATATMP = DATEADD(DAY,1,@DATATMP)
END

Leave a Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>