假设有2个表,执行顺序如下,先把table_1插入一行数据,然后用这行数据的ID(自动生成的)来更新table_2的某个列。
如下:
INSERT INTO table_1
VALUES (value1,value2,value3,...);
UPDATE table_2
SET column1=[table_1自动生成的ID]
WHERE ...
请问怎样用一条语句来写?希望可以避免第一个操作(插入)成功,但是第二个操作(更新)失败的情况。如果失败,则整体回滚。
------解决思路----------------------
-- 使用 try catch ,和 @@IDENTITY
create table a(id int identity , name varchar(10))
go
create table b(id int , a_id int check (a_id=2))
go
insert into b values(1,2)
go
declare @id int
begin tran
begin try
insert into a(name) values('张三')
select @id = @@IDENTITY
update b set a_id = @id
commit
print 'Success!'
end try
begin catch
rollback
print 'Failure!'
end catch
go
select * from a
go
select * from b
go
drop table a,b
go
(1 行受影响)
(1 行受影响)
(0 行受影响)
Failure!
id name
----------- ----------
(0 行受影响)
id a_id
----------- -----------
1 2
(1 行受影响)