怎么实现以下效果?create  proc p1
as
  exec p2
if 本过程出错 or p2内部出错 
rollback tran
else
commit tran
-----------------------------------
create  proc p2
as可能出错代码

解决方案 »

  1.   

    create  proc p1 
    as 
     begin
      begin tran
      exec p2 
     if @@error=0
        commit
     else 
        rollback
     end
      

  2.   


    p1 的@@error没有累加p2里的错误数的吧我没表达清楚,其实我想要的效果是:create  proc p1 
    as 
      exec p2 
      exec p3 ------------------在运行p1后,无论是p1、p2、p3任何一个过程出错,就要三个过程同时回滚!
    简单说就是要么三个过程都执行,要么都不执行
      

  3.   

    最前面加上SET XACT_ABORT ON
    只要有错就回滚了
      

  4.   


    create  proc p1 
    as 
      exec p2 
    SET XACT_ABORT ON
    ----------------------------------- 
    create  proc p2 
    as 
      

  5.   

    本帖最后由 zjcxc 于 2009-01-09 11:56:59 编辑
      

  6.   

    对于 2 楼的, 下面的测试就可以令你的存储过程工作不成功create proc p2
    as
    select 1/0 -- 这里失败
    select 1 -- 这里成功
    go
    create  proc p1 
    as 
     begin
      begin tran
      exec p2 
     if @@error=0 -- 则这里由于最后一个语句是成功的, 所以这个值为 0
     begin
        commit
        print 'commit'
     end
     else 
     begin
        rollback
        print 'rollback'
     end
     end
     go
     
     exec p1
     go
     
     drop proc p1, p2
      

  7.   

    如果 p2 中没有做错误处理, 可以考虑下面的方法create proc p2
    as
    select 1/0 -- 这里失败
    select 1 -- 这里成功
    go
    create  proc p1 
    as 
     begin
      begin tran
      declare @re int
      exec @re = p2 
     if @@error=0 and @re = 0 -- 则这里由于最后一个语句是成功的, 所以这个值为 0, 但存储过程出错后 rerun 为非 0
     begin
        commit
        print 'commit'
     end
     else 
     begin
        rollback
        print 'rollback'
     end
     end
     go
     
     exec p1
     go
     
     drop proc p1, p2
      

  8.   

    如果 p2 中有错误处理, 例如下面的, 则 p1 中无法做好错误处理例如, 下面的 p1 会导致 p2 中无法正确检测到 p1 中的错误
    create proc p2
    as
    select 1/0 -- 这里失败
    if @@error <> 0
    return 0
    select 1 -- 这里成功
    if @@error <> 0
    return 0
    go