2011-10-06 17 views
126

Come si fa a causare un ritardo nella esecuzione per un determinato numero di secondi?Come attendere 2 secondi

Questo non lo fa:

WAITFOR DELAY '00:02'; 

Qualcuno mi può aiutare con il formato?

+0

Il thread sembra attendere molto più di 2 secondi. Mi rendo conto che potrebbero volerci più di 2 secondi perché il thread continui, ma ci vuole circa 1 minuto quando si esegue su un db locale che sto usando e non ho altre attività in corso. – ChadD

+0

Questo attenderà in realtà esattamente 2 minuti. –

+2

possibile duplicato di [Sleep Command in T-SQL?] (Http://stackoverflow.com/questions/664902/sleep-command-in-t-sql) – Jesse

risposta

241

The documentation for WAITFOR() non prevede esplicitamente lay out il formato stringa richiesta.

Ciò attendere 2 secondi:

WAITFOR DELAY '00:00:02'; 

Il formato è hh:mi:ss.mmm.

17

ne dici di questo?

WAITFOR DELAY '00:00:02'; 

Se si dispone di "00:02" è interpretato come Ore: Minuti.

48

Come accennato in altre risposte, tutti i seguenti lavorerà per la sintassi della stringa basata su standard.

WAITFOR DELAY '02:00' --Two hours 
WAITFOR DELAY '00:02' --Two minutes 
WAITFOR DELAY '00:00:02' --Two seconds 
WAITFOR DELAY '00:00:00.200' --Two tenths of a seconds 

V'è anche un metodo alternativo di passare un valore DATETIME. Potresti pensare di confonderlo con lo WAITFOR TIME, ma funziona anche con WAITFOR DELAY.

Considerazioni per passare DATETIME:

  • E devono essere passati come una variabile, quindi non è più un bel one-liner.
  • Il ritardo viene misurato come il tempo trascorso Epoch ('1900-01-01').
  • Per situazioni che richiedono una quantità variabile di ritardo, è molto più facile da manipolare un DATETIME che per formattare correttamente un VARCHAR.

Come attendere 2 secondi:

--Example 1 
DECLARE @Delay1 DATETIME 
SELECT @Delay1 = '1900-01-01 00:00:02.000' 
WAITFOR DELAY @Delay1 

--Example 2 
DECLARE @Delay2 DATETIME 
SELECT @Delay2 = dateadd(SECOND, 2, convert(DATETIME, 0)) 
WAITFOR DELAY @Delay2 

Una nota su di attesa per TIME vs DELAY:

Avete mai notato che se si passa accidentalmente WAITFOR TIME una data che già passato, anche solo di un secondo, non tornerà mai più? Check it out:

--Example 3 
DECLARE @Time1 DATETIME 
SELECT @Time1 = getdate() 
WAITFOR DELAY '00:00:01' 
WAITFOR TIME @Time1 --WILL HANG FOREVER 

Purtroppo, WAITFOR DELAY farà la stessa cosa se si passa un valore negativo DATETIME (sì, che è una cosa).

--Example 4 
DECLARE @Delay3 DATETIME 
SELECT @Delay3 = dateadd(SECOND, -1, convert(DATETIME, 0)) 
WAITFOR DELAY @Delay3 --WILL HANG FOREVER 

Tuttavia, io consiglierei comunque utilizzando WAITFOR DELAY nel corso di un tempo statico, perché si può sempre averne effettuato il ritardo è positivo e rimarrà in questo modo per tutto il tempo che ci vuole il codice per raggiungere la dichiarazione WAITFOR.

Problemi correlati