使用来自另一个表的外键将批量数据插入到两个相关的表中

问题描述

我已将一些数据从Excel文件导入到临时sql表中。然后,我尝试将所有行插入到两个相关的表中。就像这样:我的数据库中有Event和Actors表,它们之间具有多对多关系。演员已经添加。我想将所有事件添加到“事件”表中,然后将每个事件的相关性(ActorId)添加到EventActors表中。 (dbo.TempTable具有Title,ActorId列)

insert into dbo.Event (Title) 
Select Title 
From dbo.TempTable

insert into dbo.EventActor (EventId,ActorId) 
Select ScopE_IDENTITY(),ActorId                       --ScopE_IDENTITY() is for EventId
From dbo.TempTable

这段代码运行时,所有事件都插入到事件中,但是由于外键错误,关系没有插入到EventActors中。

我认为应该有一个循环。但是我很困惑。我不想为此编写C#代码。我知道在sql Server中将有一个简单但高级的解决方案。感谢您的帮助。

解决方法

使用output clause捕获新ID,并使用merge statement捕获源表和目标表。

已捕获此信息,将其重新连接到临时表以进行第二次插入。

请注意,每行需要一个唯一的ID,并且假定临时表中的1行在Event和EventActor表中都创建了1行。

-- Ensure every row has a unique id - could be part of the table create
ALTER TABLE dbo.TempTable ADD id INT IDENTITY(1,1);

-- Create table variable for storing the new IDs in
DECLARE @NewId TABLE (INT id,INT EventId);

-- Use Merge to Insert with Output to allow us to access all tables involves
-- As Insert with Output only allows access to columns in the destination table
MERGE INTO dbo.[Event] AS Target
USING dbo.TempTable AS Source
ON 1 = 0 -- Force an insert regardless
WHEN NOT MATCHED THEN
    INSERT (Title)
    VALUES (Source.Title)
    OUTPUT Source.id,Inserted.EventId
    INTO @NewId (id,EventId);

-- Insert using new Ids just created
INSERT INTO dbo.EventActor (EventId,ActorId) 
    SELECT I.EventId,T.ActorId
    FROM dbo.TempTable T
    INNER JOIN @NewId I on T.id = T.id;