在C#中開發人員可以使用TryCatch/Throw語句對錯誤進行處理,雖然在2005后,SQL Server也引入了Try/Catch語句,但是Throw沒有被移植過來。開發者需要使用RAISERROR語句將錯誤消息返回到應用程序中,對于自定義的錯誤信息,需要先在sys.Messages創建錯誤才可以
在C#中開發人員可以使用TryCatch/Throw語句對錯誤進行處理,雖然在2005后,SQL Server也引入了Try/Catch語句,但是Throw沒有被移植過來。開發者需要使用RAISERROR語句將錯誤消息返回到應用程序中,對于自定義的錯誤信息,需要先在sys.Messages創建錯誤才可以在RAISEERROR中使用。
–
在2012中,微軟終于增加了THROW語句,THROW包含三個參數(可以不用帶參數):THROW[ { error_number | @local_variable }, { message | @local_variable },{ state |@local_variable }] [ ; ]
注意:如果使用error_number參數,錯誤號碼必須大于50000小于等于 2147483647。
下面的例子將使用RAISEERROR和THROW處理被除數不能為0的錯誤:
BEGIN TRY????
SELECT? 1/0
END TRY
BEGIN CATCH??
DECLARE @msg NVARCHAR(MAX)=ERROR_MESSAGE()
RAISERROR (@msg, 16, 1)
END CATCH?
錯誤信息:
(0 row(s) affected)
Msg 50000, Level 16, State 1, Line 6
Divide by zero error encountered.
BEGIN TRY
SELECT 1/0
END TRY
BEGIN CATCH?
THROW??
END CATCH
(0 row(s) affected)
Msg 8134, Level 16, State 1, Line 2
Divide by zero error encountered.?
THROW也可以不在TRY/CATCH塊中使用:
sp_addmessage @msgnum= 51000,
????????????? @severity =1,
????????????? @msgtext =N’i am wrong’;
GO
THROW 51000, ‘i am wrong’, 1;
結果:
Msg 51000, Level 16, State 1, Line 1
i am wrong
RAISERROR和Throw的不同:
RAISERROR statement
THROW statement
If? a msg_id is? passed to RAISERROR, the ID must be defined in sys.messages.
The? error_number? parameter does not have to be defined in sys.messages.
The? msg_str? parameter can containprintf formatting styles.
The? message? parameter does not acceptprintf style formatting.
The? severity? parameter specifies the severity of the exception.
There? is no severity? parameter.The exception severity is always set to 16.