怎么等待2秒?

时间:2011-10-06 14:52:55

标签: sql-server sql-server-2008 tsql

如何在指定的秒数内导致延迟执行?

这不能做到:

WAITFOR DELAY '00:02';

正确的格式是什么?

3 个答案:

答案 0 :(得分:302)

The documentation for WAITFOR()没有明确规定所需的字符串格式。

这将等待2秒钟:

WAITFOR DELAY '00:00:02';

格式为hh:mi:ss.mmm

答案 1 :(得分:78)

As mentioned in other answers, all of the following will work for the standard string-based syntax. 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 There is also an alternative method of passing it a DATETIME value. You might think I'm confusing this with WAITFOR TIME, but it also works for WAITFOR DELAY. Considerations for passing DATETIME: It must be passed as a variable, so it isn't a nice one-liner anymore. The delay is measured as the time since the Epoch ('1900-01-01'). For situations that require a variable amount of delay, it is much easier to manipulate a DATETIME than to properly format a VARCHAR. How to wait for 2 seconds: --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 A note on waiting for TIME vs DELAY: Have you ever noticed that if you accidentally pass WAITFOR TIME a date that already passed, even by just a second, it will never return? Check it out: --Example 3 DECLARE @Time1 DATETIME SELECT @Time1 = getdate() WAITFOR DELAY '00:00:01' WAITFOR TIME @Time1 --WILL HANG FOREVER Unfortunately, WAITFOR DELAY will do the same thing if you pass it a negative DATETIME value (yes, that's a thing). --Example 4 DECLARE @Delay3 DATETIME SELECT @Delay3 = dateadd(SECOND, -1, convert(DATETIME, 0)) WAITFOR DELAY @Delay3 --WILL HANG FOREVER However, I would still recommend using WAITFOR DELAY over a static time because you can always confirm your delay is positive and it will stay that way for however long it takes your code to reach the WAITFOR statement.

答案 2 :(得分:22)

这个怎么样?

WAITFOR DELAY '00:00:02';

如果您有“00:02”,它会将其解释为小时:分钟。