日期:2014-05-18  浏览次数:20471 次

同时写入两张表并关联ID
要将一些信息分别写入两张表A,B
B中的ID要等于A中的ID,A中的ID为自增
要怎么写比较方便?

------解决方案--------------------
declare @returnid int
insert into A ……
select returnid = @@identity
insert into B ……

应该可以一次成功插入两张表。
------解决方案--------------------
SQL code
create table a
(
   id int primary key identity(1,1),
   name varchar(50)
)
create table b
(
   id int primary key,
   name varchar(50)
)

declare @returnID int
insert into a (name) values ('testa')
select @returnID=@@identity --获取a中插入的数据的ID
insert into b (id,name) values (@returnID,'testb')

select * from a
select * from b

drop table a
drop table b