t-sqlgotoraiseerror

SQL GOTO statement in a script with multiple GO


I need to exit a SQL script without an error if a certain condition holds true. I've read that 1 solution would be to raiseerror with error code 20+ and with log parameter. But the limitation for that is that i can execute that only as an admin and the connection to the db will be aborted.

Also, I tried using GOTO and jump to the end-of-the-script, but it doesnt work, because I have multiple GO in the middle of the script. Is there a another solution?

IF <some condition> BEGIN
GOTO Finished;
END
GO

Finished:
SELECT 'Done'

Thanks!


Solution

  • goto cannot jump past a go. You'd have to retest the condition in each block:

    IF NOT <some condition> 
    BEGIN
       ...
    END
    GO
    IF NOT <some condition> 
    BEGIN
       ...
    END
    GO
    IF NOT <some condition> 
    ...