![](/img/trans.png)
[英]How to Insert xml top level attribute nodes using a column value from other table in SQL server
[英]How can return identity column value from table and insert other table in SQL Server?
我是 SQL Server 的初學者,在我的數據庫中我有兩個表:
bigint identity(1, 1)
table1ID
表 2。 我想插入(到表 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;
但是我該如何實現呢?
嘗試這個:
-- 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;
你可以試試這個:
insert into TableOne values ('abc');
insert into tableTwo values ((select SCOPE_IDENTITY()));
select SCOPE_IDENTITY()
會為您提供最后插入的 ID。
看到這個SQL 小提琴
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.