将两个插入与子查询混合?

mix two insert with subquery?

我正在向数据库中插入数据,有

单元链

[id],[FK_Unit],[DateIn],[DateOut]

和个人

[FK_VW_PERSONNAL],[FK_UnitChaine]

这里我有一个创建的 FK_VW_PERSONNAL id 列表,我必须将它们插入 Personnal 和 UnitChain。

我可以插入 UnitChains 然后获取插入的 id 然后创建 personnal:

INSERT INTO [dbo].[pstl_UnitChaine]
           ([FK_Unit]
           ,[DateIn]
           ,[DateOut])
     VALUES
           (1
           ,NOW
           ,NULL)

然后搜索插入的[pstl_UnitChaine]的[id]并插入新的人员:

INSERT INTO [Personnal]
           ([FK_VW_PERSONNAL]
           ,[FK_UnitChaine])
     VALUES
           (id from my list
           ,id I found from insert)

但我想有一个最快的方法来做到这一点,我不是 SQL 杀手,所以如果你能指导我/解释一些可以改善编码痛苦的东西,那就是太棒了:-)

编辑: 在 PaulFrancis 提议后我遇到了一个问题:

There are fewer columns in the INSERT statement than values specified in the VALUES clause. The number of values in the VALUES clause must match the number of columns specified in the INSERT statement.

插入 [pstl_UnitChaine] 后的第二个插入 juste:

INSERT INTO [dbo].[Personnal] ([FK_VW_PERSONNAL].[FK_UnitChaine]) VALUES (2118, SCOPE_IDENTITY())

你可以利用IDENTITY。只需确保您 INSERT 的 UnitChain 在执行此操作之前发生。

INSERT INTO [dbo].[pstl_UnitChaine]
       ([FK_Unit]
       ,[DateIn]
       ,[DateOut])
 VALUES
       (1
       ,NOW
       ,NULL)

INSERT INTO [Personnal]
       ([FK_VW_PERSONNAL]
       ,[FK_UnitChaine])
 VALUES
       (100
       ,SCOPE_IDENTITY())

SCOPE_IDENTITY() 获取范围内发生的 INSERT 的标识。