TRY and RAISERROR in T-SQL

不羁的心 提交于 2019-12-08 14:34:03

问题


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!


回答1:


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



回答2:


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



回答3:


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


来源:https://stackoverflow.com/questions/1131406/try-and-raiserror-in-t-sql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!