当前位置: 代码迷 >> ASP.NET >> 同时写入两张表并关联ID,该如何处理
  详细解决方案

同时写入两张表并关联ID,该如何处理

热度:381   发布时间:2013-02-25 00:00:00.0
同时写入两张表并关联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 intinsert into a (name) values ('testa')select @returnID=@@identity --获取a中插入的数据的IDinsert into b (id,name) values (@returnID,'testb')select * from aselect * from bdrop table adrop table b
  相关解决方案