使用主键、外键重复插入

Repeated inserts with Primary key, foreign key(使用主键、外键重复插入)
本文介绍了使用主键、外键重复插入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

谁能告诉我如何使用主键和外键在两个表上重复多次插入这就是我所做的.这是需要完成的工作的一小部分.StatusTable 大约有 200 行.我正在尝试将此状态表的详细信息拆分为 2-表 1、表 2.

Can anyone tell me how to do repeated multiple inserts on two tables with primary key, foreign key Here's what I've done. This is a very snippet of what needs to be done. StatusTable has around 200 rows. I am trying to split the details of this Status table into 2- Table1, Table2.

在将每条记录插入到 Table1 之后,我得到了 Identity 列,这需要用一些额外的东西插入到 Table2 中.因此,如果 StatusTable 中有 200 行,则 Table1、Table2 中有 200 行.

After inserting each record into Table1, I am getting the Identity column and this needs to be inserted into Table2 with some additional stuff. So if there are 200 rows in StatusTable there are 200 in Table1, Table2.

但这不是它的工作方式.它将所有 200 行插入到 Table1,然后获取标识,然后将一行插入到 Table2.我知道它为什么这样做.但不知道如何解决它..

But thats not the way it is working. It is inserting all the 200 rows into Table1, then getting the Identity and then inserting a single row into Table2. I know why it is doing this. But not sure how to fix it..

     INSERT INTO [dbo].[Table1]
               ([UserID],  
               ,[FirstName].......)
     SELECT 'User1' AS [UserID]
               ,'FirstName'
     FROM [dbo].[StatusTable]

     SELECT @id =  SCOPE_IDENTITY()

     INSERT INTO [dbo].[Table2]
                ([AccountID],[Status]
           values (@id, 'S')

请推荐

推荐答案

使用 OUTPUT 子句

Use the OUTPUT clause

 DECLARE @IDS TABLE (id INT) 

 INSERT INTO [dbo].[Table1]
               ([UserID]  
               ,[FirstName])
     OUTPUT inserted.id INTO @IDS          
     SELECT 'User1' AS [UserID]
               ,'FirstName'
     FROM [dbo].[StatusTable]

     INSERT INTO [dbo].[Table2]
                ([AccountID],[Status])
         SELECT Id, 'S' FROM @IDS

这篇关于使用主键、外键重复插入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Execute complex raw SQL query in EF6(在EF6中执行复杂的原始SQL查询)
auto_increment column for a group of rows?(一组行的AUTO_INCREMENT列?)
SSIS: Model design issue causing duplications - can two fact tables be connected?(SSIS:模型设计问题导致重复-两个事实表可以连接吗?)
SQL Server Graph Database - shortest path using multiple edge types(SQL Server图形数据库-使用多种边类型的最短路径)
Invalid column name when using EF Core filtered includes(使用EF核心过滤包括时无效的列名)
How should make faster SQL Server filtering procedure with many parameters(如何让多参数的SQL Server过滤程序更快)