How to Stop the Execution of a Stored Procedure Using Sql Server?

Lets say I have a stored procedure which has a simple IF block. If the performed check meets the criteria, then I want to stop the procedure from further execution.

What is the best way to do this?

Here is the code:

IF EXISTS (<Preform your Check>)
BEGIN
    // NEED TO STOP STORED PROCEDURE EXECUTION
END
ELSE
BEGIN
    INSERT ()...
END

Thanks for any help with this!

2 Answers

Just make a call to RETURN:

IF EXISTS (<some condition>)
BEGIN
    // NEED TO STOP STORED PROCEDURE EXECUTION
    RETURN
END

This will return the control back to the caller immediately - it skips everything else in the proc.

1

You could simply put a jump label at the end of the SP body, and issue a GOTO in the first IF statement. Alternatively, you can extend the first BEGIN ... END block to contain the entire rest of the SP body, and reverse the condition (IF NOT EXISTS...).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

James H. Sterling

James H. Sterling

Environmental Science & Climate Journalist

James Sterling reports on renewable energy developments, climate policy, ecological conservation, and green tech innovations around the globe.

Share this article
Twitter Facebook Pinterest