The WAITFOR statement in SQL Server is used to introduce a delay or wait period in the execution of a batch, transaction, or query.
WAITFOR DELAY '00:00:05'; -- Pauses execution for 5 seconds
BEGIN
SELECT 'Hellow' --Run after 5 second
END
WAITFOR TIME '12:00:00'; -- Pauses execution until 12 PM
BEGIN
SELECT 'Hellow' --Run after 5 second
END
DECLARE @targetTime DATETIME = '2024-05-06 15:30:00';
WAITFOR TIME @targetTime; -- Pauses execution until 3:30 PM on May 6th, 2024
WAITFOR with RECEIVE
In Service Broker, WAITFOR can be used in conjunction with the RECEIVE statement to wait for messages to arrive in a queue.
WAITFOR (
RECEIVE * FROM QueueName
), TIMEOUT 1000; -- Waits for 1 second for a message to arrive in the queue