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

Insert bulk data into two related tables with foreign keys from another table

我已将一些数据从 Excel 文件导入临时文件 SQL table。然后我尝试将所有行插入到两个相关的 table 中。就像这样:在我的数据库中有具有多对多关系的 Events 和 Actors tables。演员已经添加。我想将所有事件添加到 Events table,然后将每个事件的关系(ActorId)添加到 EventActors tables。 (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

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

我认为应该有一个循环。但我很困惑。我不想为此编写 C# 代码。我知道在 SQL 服务器中会有一个简单但高级的解决方法。感谢您的帮助。

使用 output clause to capture the new IDs, with a merge statement 允许从源和目标 table 进行捕获。

捕获此信息后,将其返回到临时 table 以进行第二次插入。

请注意,每行需要一个唯一的 ID,这假设临时 table 中的 1 行在 Event 和 EventActor tables 中创建了 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;