在CODE时,遇到一个问题,就是两个表的更新\插入操作时的事务:
问题是这样的.有表A,B结构如下:
  TABLE A的结构为: A_ID,A-NAMEID,.........
  TABLE B的结构为: B_ID,A_ID(引用A表的唯一键),B_NAME,......
  之年以采取这种结构主要是为了数据结构好看一点:
  但如何写一个事务,让更新或插入A,B两个表中另 一个失败时,回滚事务呢?
  另外,这个事务写在哪里,写在存储过程里,或是写在SQL语句中呢.
请指教.

解决方案 »

  1.   

    if object_id('表a') is not null
    drop table 表a
    go
    if object_id('表b') is not null
    drop table 表b
    go
    create table 表a(name varchar(20) not null)
    create table 表b(name varchar(20))begin   try
    begin   tran
    insert into 表a select null
    insert into 表b select 'c'
    commit  tran
    end   try
    begin catch 
    rollback
    end catch
    --全部回滚写存储过程里
      

  2.   

    1,建立引用约束
    2,不同的表,但在同一库中,那么直接写就可以了,不像跨库要分布式事务。begin tran
    declare @aid int
    insert tableA select ....
    if @@error!=0
       rollback tran
    else
    begin
       select @aid=scope_identity()
       insert tableB select ...,@aid,...
       if @@error!=0
           rollback tran
       else
           commit tran
    end可能手误
      

  3.   

    begin tran
    你的语句if @@error>0
    begin
    rollback tran
    end
    else
    begin
    commit tran
    end