存储过程事物的处理

一般情况在proc中判断的处理我们都采用

if not exists(select 1 from aa where a= 1)
begin
    select '错误'
    return
end

 

而在tran中我们最好用抛异常的方式

begin try
 update Table set a = a where b =1

 if @@rowcount = 0 and @@ERROR > 0
 begin
    SET @vcResult = '失败'
    RAISERROR(@vcResult,16,1)
 end

 insert into Table(a,b,c)value('a','b','c')
 if @@rowcount = 0 and @@ERROR > 0
 begin
    SET @vcResult = '失败'
    RAISERROR(@vcResult,16,1)
 end
end try
begin catch
--如果proc中有嵌套的proc,而嵌套的proc中也写有try-catch 则写IF @@tranCount =1
print error_message() --测试打印错误
IF @@tranCount >0    ROLLBACK TRAN ; 
SELECT @vcResult AS vcResult  
end catch