In order to delay the execution of any query, we can use the WAITFOR keyword in SQL Server. This keyword along with the DELAY and TIME keywords can be used to either delay the execution of the query (subsequent to WAITFOR statement) for a specific time period or delay the execution, until a specific time is met. Let's see how we can use it.
WAITFOR with Delay
When using Delay keyword, along with WAITFOR, the subsequent queries will not be specified. It is quite similar to Thread.Sleep in C#. For example, the following select statement will not be executed for 1 minute and 15 seconds.
- WAITFOR DELAY '00:01:15';
-
- SELECT * FROM Employees
The syntax here is 'hh:mm:ss'.
WAITFOR with Time
When using the Time keyword, the subsequent query will not execute until the specified time is met. It is like delaying the execution of the query until the specified time has been reached. For example, the following select statement be executed at 11 A.M. in the morning.
- WAITFOR TIME '11:05:10';
-
- SELECT * FROM Employees
The syntax here is again same i.e. 'hh:mm:ss'. However, this will specify a time when the query should execute, when the current batch/procedure starts to execute.
I hope you enjoyed reading this. Happy querying.