Transact-SQL 代码中的错误可使用 TRY…CATCH 构造处理,此功能类似于C#语言的异常处理功能。TRY…CATCH 构造包括两部分:一个 TRY 块和一个 CATCH 块
1.TRY...CATCH 块不处理导致数据库引擎关闭连接的严重性为 20 或更高的错误。但是,只要连接不关闭,TRY...CATCH 就会处理严重性为 20 或更高的错误。
2.严重性为 10 或更低的错误被视为警告或信息性消息,TRY...CATCH 块不处理此类错误。
对于与TRY...CATCH 构造在同一执行级别发生的错误,TRY...CATCH 将不处理以下两类错误:
1.编译错误,例如阻止批处理执行的语法错误。
2.语句级重新编译过程中出现的错误,例如由于名称解析延迟而造成在编译后出现对象名解析错误。
--由SELECT 语句生成的对象名解析错误是不被TRY…CATCH 构造捕捉
BEGIN TRY
-- Table does not exist
SELECT * FROM Table1;
END TRY
BEGIN CATCH
SELECT
ERROR_NUMBER() AS ErrorNumber,
ERROR_SEVERITY() AS ErrorSeverity,
ERROR_STATE() AS ErrorState,
ERROR_PROCEDURE() AS ErrorProcedure,
ERROR_LINE() AS ErrorLine,
ERROR_MESSAGE() AS ErrorMessage;
END CATCH
BEGIN TRY
-- Table does not exist
SELECT * FROM Table1;
END TRY
BEGIN CATCH
SELECT
ERROR_NUMBER() AS ErrorNumber,
ERROR_SEVERITY() AS ErrorSeverity,
ERROR_STATE() AS ErrorState,
ERROR_PROCEDURE() AS ErrorProcedure,
ERROR_LINE() AS ErrorLine,
ERROR_MESSAGE() AS ErrorMessage;
END CATCH
如果某个错误在 TRY 块内的编写或语句级别重新编写过程中并在较低的执行级别(例如,执行 sp_executesql 或用户定义存储过程时)发生,则该错误会在低于 TRY…CATCH 构造的级别上发生,并由相关联的 CATCH 块处理。
CREATE PROCEDURE pr_1
AS
-- Table does not exist
SELECT * FROM Table1;
GO
BEGIN TRY
EXECUTE pr_1
END TRY
BEGIN CATCH
SELECT
ERROR_NUMBER() AS ErrorNumber,
ERROR_SEVERITY() AS ErrorSeverity,
ERROR_STATE() AS ErrorState,
ERROR_PROCEDURE() AS ErrorProcedure,
ERROR_LINE() AS ErrorLine,
ERROR_MESSAGE() AS ErrorMessage;
END CATCH;
2007年12月3日13:53:38
--ids 主键
create table test1( ids int not null,
constraint pk_test1 primary key(ids)
)
go
select * from test1
begin try
BEGIN TRAN
insert into test1 (ids)
select 1
insert into test1 (ids)
select 2
insert into test1 (ids)
select 1 --违反了主键约束
COMMIT TRAN
PRINT 'Transaction committed'
end try
begin catch
ROLLBACK
PRINT 'Transaction rolled back'
SELECT
ERROR_NUMBER() AS ErrorNumber,
ERROR_SEVERITY() AS ErrorSeverity,
ERROR_STATE() AS ErrorState,
ERROR_PROCEDURE() AS ErrorProcedure,
ERROR_LINE() AS ErrorLine,
ERROR_MESSAGE() AS ErrorMessage;
end catch
select * from test1
TRY...CATCH 使用下列错误函数来捕获错误信息:
ERROR_NUMBER() 返回错误号。
ERROR_MESSAGE() 返回错误消息的完整文本。此文本包括为任何可替换参数(如长度、对象名或时间)提供的值。
ERROR_SEVERITY() 返回错误严重性。
ERROR_STATE() 返回错误状态号。
ERROR_LINE() 返回导致错误的例程中的行号。
ERROR_PROCEDURE() 返回出现错误的存储过程或触发器的名称。
BEGIN TRY
SELECT 1/0;
END TRY
BEGIN CATCH
SELECT
ERROR_NUMBER() AS ErrorNumber,
ERROR_SEVERITY() AS ErrorSeverity,
ERROR_STATE() AS ErrorState,
ERROR_PROCEDURE() AS ErrorProcedure,
ERROR_LINE() AS ErrorLine,
ERROR_MESSAGE() AS ErrorMessage;
END CATCH;