如何从表中返回标识列值并在SQL Server中插入其他表?

时间:2015-10-31 09:47:00

标签: sql-server sql-server-2012

我是SQL Server的初学者,在我的数据库中我有两个表:

  • 表1,ID类型为bigint identity(1, 1)
  • 表2,列名称为table1ID

我想插入(进入表1)并生成一个id值。然后我将该id值插入表2的table1ID


我将表更改为此并写下此查询:

insert into Interconnect_Traffic_Analysis_MAIN   (Code_Op,Name_Op,Shomare_Tel,Duration,table1ID>>table1 id must save in this column) 
select  t7,t8,t9,t10 from Interconnect_Traffic_Analysis_Temp;

但我该如何实现呢?

2 个答案:

答案 0 :(得分:1)

试试这个:

-- declare a variable to hold your newly created IDENTITY value
DECLARE @Identity BIGINT

-- insert your values into the first table
INSERT INTO dbo.Table1(list-of-columns)
VALUES(list-of-values);

-- get the newly generated IDENTITY value into your variable
SET @Identity = SCOPE_IDENTITY();

-- use that variable in your second INSERT
INSERT INTO dbo.Table2(table1Id)
VALUES(@Identity)

<强>更新

使用INSERT语句更新您的问题,请使用此代码添加@Identity值:

INSERT INTO dbo.Interconnect_Traffic_Analysis_MAIN(Code_Op, Name_Op, Shomare_Tel, Duration, table1ID) 
   SELECT 
       t7, t8, t9, t10, @Identity 
   FROM
       Interconnect_Traffic_Analysis_Temp;

答案 1 :(得分:0)

你可以试试这个:

insert into TableOne values ('abc');
insert into tableTwo values ((select SCOPE_IDENTITY()));

select SCOPE_IDENTITY()会为您提供最后插入的ID。

请参阅此SQL fiddle