Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TRY and RAISERROR in T-SQL

Having a small issue and wondering if I'm using these correctly.

In my SQL script is have

BEGIN TRY
    // check some information and if there are certains errors
    RAISERROR ('Errors found, please fix these errors and retry', 1, 2) WITH SETERROR

    // Complete normal process if no errors encountered above
    PRINT 'IMPORT SUCCEEDED'
END TRY
BEGIN CATCH
    PRINT 'IMPORT ABORTED. ERRORS ENCOUNTERED'
END CATCH

However, this is encountering an error and then continuing with the rest of the script. What am I missing? Thanks!

like image 592
StevenMcD Avatar asked Jul 15 '09 13:07

StevenMcD


3 Answers

It's because the severity of the RAISERROR is not high enough, needs to be between 11 and 19, as described here

e.g.

RAISERROR ('Errors found, please fix these errors and retry', 16, 2) WITH SETERROR
like image 186
AdaTheDev Avatar answered Nov 17 '22 07:11

AdaTheDev


I think you need to raise an error with a severity level higher than 10 for it to be caught, e.g.

RAISERROR ('Errors found', 11, 2) WITH SETERROR
like image 33
Alex Peck Avatar answered Nov 17 '22 06:11

Alex Peck


From MSDN


severity

Is the user-defined severity level associated with this message. Severity levels from 0 through 18 can be used by any user. Severity levels from 19 through 25 are used only by members of the sysadmin fixed server role. For severity levels from 19 through 25, the WITH LOG option is required.

Caution Severity levels from 20 through 25 are considered fatal. If a fatal severity level is encountered, the client connection is terminated after receiving the message, and the error is logged in the error log and the application log.


Try this instead:

RAISERROR ('Errors found, please fix these errors and retry', 1, 2) WITH SETERROR
RETURN
like image 5
Jim Carnicelli Avatar answered Nov 17 '22 05:11

Jim Carnicelli