Transact-SQL 代码中的错误可使用 TRY…CATCH 构造处理,此功能类似于C#语言的异常处理功能。TRY…CATCH 构造包括两部分:一个 TRY 块和一个 CATCH 块 

  1.TRY...CATCH 块不处理导致数据库引擎关闭连接的严重性为 20 或更高的错误。但是,只要连接不关闭,TRY...CATCH 就会处理严重性为 20 或更高的错误。 

  2.严重性为 10 或更低的错误被视为警告或信息性消息,TRY...CATCH 块不处理此类错误。 

1--ids 主键 2createtable test1( ids intnotnull,
3constraint pk_test1 primarykey(ids)
4)
5go
6select*from test1
7begin try
89BEGINTRAN10insertinto test1 (ids)
11select11213insertinto test1 (ids)
14select21516insertinto test1 (ids)
17select1--违反了主键约束 1819COMMITTRAN20PRINT'Transaction committed'
21end try
22begin catch
23ROLLBACK24PRINT'Transaction rolled back'2526SELECT27 ERROR_NUMBER() AS ErrorNumber,
28 ERROR_SEVERITY() AS ErrorSeverity,
29 ERROR_STATE() AS ErrorState,
30 ERROR_PROCEDURE() AS ErrorProcedure,
31 ERROR_LINE() AS ErrorLine,
32 ERROR_MESSAGE() AS ErrorMessage;
33end catch
34
35select*from test1
36

  TRY...CATCH 使用下列错误函数来捕获错误信息: 

  ERROR_NUMBER() 返回错误号。 

  ERROR_MESSAGE() 返回错误消息的完整文本。此文本包括为任何可替换参数(如长度、对象名或时间)提供的值。 

  ERROR_SEVERITY() 返回错误严重性。 

  ERROR_STATE() 返回错误状态号。 

  ERROR_LINE() 返回导致错误的例程中的行号。 

  ERROR_PROCEDURE() 返回出现错误的存储过程或触发器的名称。 

1BEGIN TRY
2SELECT1/0;
3END TRY
4BEGIN CATCH
5SELECT6 ERROR_NUMBER() AS ErrorNumber,
7 ERROR_SEVERITY() AS ErrorSeverity,
8 ERROR_STATE() AS ErrorState,
9 ERROR_PROCEDURE() AS ErrorProcedure,
10 ERROR_LINE() AS ErrorLine,
11 ERROR_MESSAGE() AS ErrorMessage;
12END CATCH;
13


  对于与TRY...CATCH 构造在同一执行级别发生的错误,TRY...CATCH 将不处理以下两类错误: 

  1.编译错误,例如阻止批处理执行的语法错误。 

  2.语句级重新编译过程中出现的错误,例如由于名称解析延迟而造成在编译后出现对象名解析错误。 
 

1--由SELECT 语句生成的对象名解析错误是不被TRY…CATCH 构造捕捉 2BEGIN TRY
3-- Table does not exist 4SELECT*FROM Table1;
5END TRY
6BEGIN CATCH
7SELECT8 ERROR_NUMBER() AS ErrorNumber,
9 ERROR_SEVERITY() AS ErrorSeverity,
10 ERROR_STATE() AS ErrorState,
11 ERROR_PROCEDURE() AS ErrorProcedure,
12 ERROR_LINE() AS ErrorLine,
13 ERROR_MESSAGE() AS ErrorMessage;
14END CATCH
15

如果某个错误在 TRY 块内的编写或语句级别重新编写过程中并在较低的执行级别(例如,执行 sp_executesql 或用户定义存储过程时)发生,则该错误会在低于 TRY…CATCH 构造的级别上发生,并由相关联的 CATCH 块处理。