2017-04-12 63 views
0

兄弟,你能幫助我嗎? 示例查詢:如何從表中獲取多個scope_identity然後插入到其他表?

 DECLARE @id_scope TABLE (ID_TBA_PK int) 
    Insert into TABLE_A 
     Select ID_TBA_PK,ID_LET_FK,NAME, ADDRESS FROM TABLE_A WHERE 
     [email protected]_LET_FK 
     set @id_scope = scope_identity() --but must get multiple identity 
     -- because above insert multiple,ID_TBA_PK is autoincement. 

然後插入到表其他:

insert into TABLE_B 
       select [email protected]_scope , NAME, ADDRESS FROM TABLE_B 
       WHERE [email protected]_TBA_FK 

    --(MULTIPLE INSERT TO TABLE_B) 
+0

HII它似乎您試圖插入多行詳細列表例如:-Table_B是你的Detail.my問題是#id_scope對於所有行都是相同的,否則它將改變。假設第一行#id_scope是10,因此對於下一行它將是11或10. –

回答

1

OUTPUT條款添加到您的INSERT。事情是這樣的:

INSERT TABLE_A(NAME, ADDRESS, etc.) OUTPUT Inserted.ID_TBA_PK into @id_scope Select ID_TBA_PK,ID_LET_FK,NAME, ADDRESS FROM TABLE_A WHERE [email protected]_LET_FK

此行我假設ID_TBA_PK是你的新身份

OUTPUT Inserted.ID_TBA_PK into @id_scope

所以一般情況下是

INSERT [table] (columns) 

OUTPUT INSERTED.[column] into [@other table] 

SELECT columns from ..... 
+0

我填寫您的查詢在我的查詢兄弟? –

+0

編輯爲(我希望)更有幫助 – LoztInSpace

+0

@id_scope如何插入到表別人?,看看我的問題上面。 –

相關問題