RAISERROR (Transact-SQL)的用法

A. 从 CATCH 块返回错误消息

以下代码示例显示如何在 RAISERROR 块中使用 TRY 使执行跳至关联的 CATCH 块中。 它还显示如何使用 RAISERROR 返回有关调用 CATCH 块的错误的信息。

RAISERROR 仅能生成状态为 1 到 127 的错误。 由于数据库引擎可能引发状态为 0 的错误,因此,建议您先检查由 ERROR_STATE 返回的错误状态,然后将它作为一个值传递给状态参数 RAISERROR。

BEGIN TRY  
    -- RAISERROR with severity 11-19 will cause execution to   
    -- jump to the CATCH block.  
    RAISERROR ('Error raised in TRY block.', -- Message text.  
               16, -- Severity.  
               1 -- State.  
               );  
END TRY  
BEGIN CATCH  
    DECLARE @ErrorMessage NVARCHAR(4000);  
    DECLARE @ErrorSeverity INT;  
    DECLARE @ErrorState INT;  
  
    SELECT   
        @ErrorMessage = ERROR_MESSAGE(),  
        @ErrorSeverity = ERROR_SEVERITY(),  
        @ErrorState = ERROR_STATE();  
  
    -- Use RAISERROR inside the CATCH block to return error  
    -- information about the original error that caused  
    -- execution to jump to the CATCH block.  
    RAISERROR (@ErrorMessage, -- Message text.  
               @ErrorSeverity, -- Severity.  
               @ErrorState -- State.  
               );  
END CATCH;  

  

B. 在 sys.messages 中创建即席消息
以下示例显示如何引发 sys.messages 目录视图中存储的消息。 该消息通过 sp_addmessage 系统存储过程,以消息号 50005 添加到 sys.messages 目录视图中。

sp_addmessage @msgnum = 50005, 
@severity = 10, 
@msgtext = N'<\<%7.3s>>'; 
GO 
RAISERROR (50005, -- Message id. 
10, -- Severity, 
1, -- State, 
N'abcde'); -- First argument supplies the string. 
-- The message text returned is: << abc>>. 
GO 
sp_dropmessage @msgnum = 50005; 
GO

  

 

posted @ 2021-01-12 10:42  奥兰王子  阅读(136)  评论(0编辑  收藏  举报