插入多个表的事务处理,该如何做?谢谢

jz1979 2006-09-21 11:11:35
如:
要向两个表插入数据,
首先插入表1成功时,获得表1的ID,再向表2插入数据;
如果表2插入失败,
则表2和表1都回滚到原始状态

该如何做?
...全文
195 1 打赏 收藏 转发到动态 举报
写回复
用AI写文章
1 条回复
切换为时间正序
请发表友善的回复…
发表回复
gahade 2006-09-21
  • 打赏
  • 举报
回复
create table table1(id int identity(1,1),code varchar(10))
create table table2(id int primary key)

begin tran
insert into table1(code)
select 'aaa'
declare @id int
select @id=@@identity
insert into table2(id)
select @id
if @@rowcount>=1 and @@error=0
commit
else
rollback tran
--上面这部分会执行成功

begin tran
insert into table1(code)
select 'bbb'
declare @id int
select @id=@@identity
insert into table2(id)
select 1
if @@rowcount>=1 and @@error=0
commit
else
rollback tran
--上面这部分会执行失败,table1和table2都会回滚

drop table table1
drop table table2

22,209

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server 疑难问题
社区管理员
  • 疑难问题社区
  • 尘觉
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧