Go to Top

Stop a MSSQL query

Following on from my earlier post today about I figured I should include this post purely on how to stop a MSSQL query if there are results as this is mentioned in my other blog post.

I’m always looking for ways to streamline processes and I see no use in continuing to run queries if they are not actually going to affect any records therefore I believe it’s important to see if something is going to have any effect prior to doing it.

This has an advantage in more than one ways, time being the main factor, why use up time and processing power executing a query if it isn’t actually going to make any changes, thats why I feel it’s important to stop a MSSQL query if it’s not going to have any effect.

To prevent a second query from executing based on the result of the query above it you can use the BEGIN, RETURN and END statements.

The example i’ll use is the same example i’ve used in my other post about .

IF (SELECT count(*) FROM people WHERE status = '0') > 1
UPDATE people
SET status = 'archive'
WHERE status = '0'
SELECT 'No people with status 0'

UPDATE account
SET accountstatus = 'archive'
WHERE accountid IN (SELECT id FROM people WHERE status = 'archive')

If there were any people found with the status of 0 the first query will update all those to a status of archive. After this it will go ahead and perform the second query where it updates any accounts to a status of archive where the accountid appears in the id of people who’s status has just been set to archive.

However, what BEGIN, RETURN and END will do is stop executing the query if there are no people with a status of 0, this means the second part of the query won’t run and this will save on processing time, after all, if the first query doesnt update anything there is absolutely no need for the second query to even run.

This is a very simple example of the query to help you understand the basics of how they work and allow you to adapt it for yourself.

If you have any questions feel free to ask below.

Leave a Reply

Your email address will not be published. Required fields are marked *

+ 8 = ten