Home > Database > Mysql Tutorial > SQL Server 2012 错误处理增强THROW

SQL Server 2012 错误处理增强THROW

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
Release: 2016-06-07 17:59:09
Original
1079 people have browsed it

在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.
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Issues
sql file
From 1970-01-01 08:00:00
0
0
0
php - Overhead of prepare vs sql?
From 1970-01-01 08:00:00
0
0
0
Print sql statement
From 1970-01-01 08:00:00
0
0
0
Pass array to SQL insert query using PHP
From 1970-01-01 08:00:00
0
0
0
sql optimization or
From 1970-01-01 08:00:00
0
0
0
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template