SQL Server 2005 TSQL 学习笔记:Try Catch

用处:提供和C#一样的错误处理机制,不过没有finally块.try catch可以嵌套使用.如果错误被catch中处理过,后面的语句去继续运行.

语法:
begin try
...
end try
begin catch
...
end catch

简单示例:

 

begin try
    
begin try
        
exec sp_executesql N'select * from tables'
    
end try
    
begin catch
        
print 'execute sql error'
    
end catch

    
insert into Region(RegionID, RegionDescription)
        
values (1'xxx')


    
--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

注意error相关的函数要放在catch的第一行使用.

在catch中可以使用raiserror函数,将错误通知调用的应用程序,如ADO.NET

begin try
    
exec sp_executesql N'select * from tables'
end try
begin catch
    
print 'execute sql error'
    
raiserror 130001 'error message return to caller application'
end catch
原文地址:https://www.cnblogs.com/rockniu/p/1235118.html