Blog Post

Help! My query is too fast!

,

Said no one ever. Well, maybe. I have had occasions where I needed a brief pause in the middle of a batch. For example, if I’m running a big delete I might create a loop and delete in batches. If I’m having to run this for a while on an active table I might want to put a pause in each loop for a second or two to allow other processes to get in and do whatever they need to do.

So how do we pause a batch? The WAITFOR command. With this command you can either pause execution for a specific amount of time:

-- Wait 30 seconds
WAITFOR DELAY '00:00:30'
-- Wait 1 minute
WAITFOR DELAY '00:01:00'
-- Wait 2 hours
WAITFOR DELAY '02:00:00'

Or tell it to wait for a specific time. Be aware this isn’t overly precise but it can be useful if you want to run multiple batches at approximately the same time.

-- Wait until 5pm
WAITFOR TIME '5:00 PM'

And in case you run into a development team that complains that when they time their code the duration is all over the place, this little gem will make sure their query will always take the same amount of time (assuming normal run time is under 90 seconds).

DECLARE @Delay datetime = dateadd(second,90,getdate())
-- Your query here
SELECT * FROM sys.databases
IF @Delay > getdate()
WAITFOR TIME @Delay

Filed under: DBA Humor, Microsoft SQL Server, SQLServerPedia Syndication, T-SQL Tagged: Humor, microsoft sql server, T-SQL

Rate

You rated this post out of 5. Change rating

Share

Share

Rate

You rated this post out of 5. Change rating