How to make SQL script to sleep?

In my previous article, we have seen the ways to make a PHP script to sleep for a short period of time. In this article, we will see the way to make an SQL Script to sleep for some time.

To make the SQL block to sleep, you can use the SQL Server’s inbuilt control flow Transact-SQL element called WAITFOR. Using WAITFOR along with the DELAY argument, you can block the execution of the SQL scripts. The syntax is:

WAITFOR DELAY hh:mm[[:ss].mss]

Here is an example

In the below given example, after executing the first GETDATE() statement, the execution process will wait for 1 minute and then continue. This will make the remaining SQL script to sleep for 1 minute.

SELECT GETDATE()

WAITFOR DELAY '00:01'  -- Sleep for 1 minute

SELECT GETDATE()
GO
Make SQL script to sleep

To make sql script to sleep for 1 second

SELECT GETDATE()

WAITFOR DELAY '00:00:01'  -- Sleep for 1 second

SELECT GETDATE()
GO

To sleep in milliseconds

SELECT GETDATE()

WAITFOR DELAY '00:00:00.600'  -- Sleep for 600 milliseconds

SELECT GETDATE()
GO

Note: The precision of the WAITFOR is around 15ms. So, if you try to sleep for 5ms, you may not get an accurate delay.

Reference


Leave your thoughts...

This site uses Akismet to reduce spam. Learn how your comment data is processed.