重新抛出 RAISERROR 生成的异常

你可以使用 TRHOW 语句重新抛出在 CATCH 块中捕获的错误:

DECLARE @msg nvarchar(50) = 'Here is a problem! Area: ''%s'' Line:''%i'''
BEGIN TRY
    print 'First statement';
    RAISERROR(@msg, 11, 1, 'TRY BLOCK', 2);
    print 'Second statement';
END TRY
BEGIN CATCH
    print 'Error: ' + ERROR_MESSAGE();
    THROW;
END CATCH

请注意,在这种情况下,我们使用格式化参数(第四个和第五个参数)引发错误。如果要在消息中添加更多信息,这可能很有用。执行结果是:

First statement
Error: Here is a problem! Area: 'TRY BLOCK' Line:'2'
Msg 50000, Level 11, State 1, Line 26
Here is a problem! Area: 'TRY BLOCK' Line:'2'