How to wait for 2 seconds?

后端 未结 4 2036
情深已故
情深已故 2020-12-22 19:21

How does one cause a delay in execution for a specified number of seconds?

This doesn\'t do it:

WAITFOR DELAY \'00:02\';

What is th

相关标签:
4条回答
  • 2020-12-22 20:02

    The documentation for WAITFOR() doesn't explicitly lay out the required string format.

    This will wait for 2 seconds:

    WAITFOR DELAY '00:00:02';
    

    The format is hh:mi:ss.mmm.

    0 讨论(0)
  • 2020-12-22 20:16

    Try this example:

    exec DBMS_LOCK.sleep(5);
    

    This is the whole script:

    SELECT TO_CHAR (SYSDATE, 'MM-DD-YYYY HH24:MI:SS') "Start Date / Time" FROM DUAL;
    
    exec DBMS_LOCK.sleep(5);
    
    SELECT TO_CHAR (SYSDATE, 'MM-DD-YYYY HH24:MI:SS') "End Date / Time" FROM DUAL;
    
    0 讨论(0)
  • 2020-12-22 20:17

    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.

    0 讨论(0)
  • 2020-12-22 20:21

    How about this?

    WAITFOR DELAY '00:00:02';
    

    If you have "00:02" it's interpreting that as Hours:Minutes.

    0 讨论(0)
提交回复
热议问题