简体   繁体   English

如何从另一个表插入并使用PK插入SQL Server中的多个表?

[英]How to insert from another table and using PK to insert into multiple tables in SQL Server?

I'm looking to copy info into another table but as each record is created I will be using a unique identity to generated a new PK. 我希望将信息复制到另一个表中,但是在创建每个记录时,我将使用唯一标识来生成新的PK。 I also want to use that PK to insert into another table eg 我也想使用该PK插入另一个表,例如

INSERT INTO Table1(a, b) SELECT a, b FROM TempTable 插入表1(a,b)从TempTable中选择a,b

INSERT INTO Table2(id, description) VALUES([PK From new record created in Table1], 'Test') 插入表2(id,描述)VALUES([PK从表1中创建的新记录中,'测试')

Is this possible? 这可能吗?

You should realize that your code can create more than one new record. 您应该意识到您的代码可以创建多个新记录。

The following captures all the new ids into @ids and then inserts all of them into the new table: 以下代码将所有新的id捕获到@ids ,然后将所有新的id插入新表中:

declare @ids table (int id);

insert into table1(a, b) 
    output inserted.id into @ids
    select a, b 
    from TempTable;

insert into Table2(id, description) 
    select id, 'Test'
    from @ids;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM