SQL Server 2012 錯(cuò)誤處理增強(qiáng)THROW

在C#中開發(fā)人員可以使用TryCatch/Throw語句對(duì)錯(cuò)誤進(jìn)行處理,雖然在2005后,SQL Server也引入了Try/Catch語句,但是Throw沒有被移植過來。開發(fā)者需要使用RAISERROR語句將錯(cuò)誤消息返回到應(yīng)用程序中,對(duì)于自定義的錯(cuò)誤信息,需要先在sys.Messages創(chuàng)建錯(cuò)誤才可以

在C#中開發(fā)人員可以使用TryCatch/Throw語句對(duì)錯(cuò)誤進(jìn)行處理,雖然在2005后,SQL Server也引入了Try/Catch語句,但是Throw沒有被移植過來。開發(fā)者需要使用RAISERROR語句將錯(cuò)誤消息返回到應(yīng)用程序中,對(duì)于自定義的錯(cuò)誤信息,需要先在sys.Messages創(chuàng)建錯(cuò)誤才可以在RAISEERROR中使用。

在2012中,微軟終于增加了THROW語句,THROW包含三個(gè)參數(shù)(可以不用帶參數(shù)):THROW[ { error_number | @local_variable }, { message | @local_variable },{ state |@local_variable }] [ ; ]

注意:如果使用error_number參數(shù),錯(cuò)誤號(hào)碼必須大于50000小于等于 2147483647。

下面的例子將使用RAISEERROR和THROW處理被除數(shù)不能為0的錯(cuò)誤:

BEGIN TRY????

SELECT? 1/0

END TRY

BEGIN CATCH??

DECLARE @msg NVARCHAR(MAX)=ERROR_MESSAGE()

RAISERROR (@msg, 16, 1)

END CATCH?

錯(cuò)誤信息:
(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;

結(jié)果:

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.

? 版權(quán)聲明
THE END
喜歡就支持一下吧
點(diǎn)贊14 分享