Help! My query is too fast!


September 14, 2017 by Kenneth Fisher

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

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()

One thought on “Help! My query is too fast!

  1. […] If you need your queries to be slower, Kenneth Fisher has you covered: […]

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

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

Enter your email address to follow this blog and receive notifications of new posts by email.

Join 3,755 other subscribers

Follow me on Twitter

ToadWorld Pro of the Month November 2013
%d bloggers like this: