SQL Server 2012 错误处理增强THROW


在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 

RAISERRORThrow的不同: 

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.

相关内容