RAISERROR (Transact-SQL)的用法
阿新 • • 發佈:2021-01-12
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