TRY and RAISERROR in T-SQL
Asked Answered
D

3

20

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!

Dialyse answered 15/7, 2009 at 13:28 Comment(4)
@ FailBoy - The issue that you have asked about is really T-SQL specific. If you could change your answer title to "TRY and RAISERROR in T-SQL" this would be clearer to the community. Thanks!Disqualification
I will keep that in mind for next time, I see someone, I think you, has already changed the tag to tsql :)Dialyse
@ FailBoy - I meant changing the title. I can't change the title, as I do not have edit priveleges.Disqualification
oh right, I follow now, I have changed the titleDialyse
L
35

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
Liberate answered 15/7, 2009 at 13:36 Comment(0)
J
12

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
Jon answered 15/7, 2009 at 13:39 Comment(1)
Thanks for the answer! I have marked AdaTheDev's answer as correct because he included a link for other people to be able to follow. But thanks still. UpVote +1Dialyse
K
5

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
Kilpatrick answered 23/10, 2009 at 15:7 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.