Help! My query is too fast!

1

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

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:

WordPress.com Logo

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

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s

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

Join 2,151 other followers

Follow me on Twitter

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