使用存储过程将批量数据插入 master/detail 表的最佳方法?

the best method for insert bulk data into master/detail tables with stored-procedure?

假设,我有一个 master table Order 的名称和名为 OrderDetail 的详细信息 table其中 OrderId 是身份键并在 OrderDetail 中用作外键。现在我想将带有存储过程的 批量数据 插入到 Order 中,然后将相关详细信息插入到 OrderDetail table。 谁能告诉我最好的方法吗?如何从 master 和我使用的 detail table 获取身份值?

您可以按如下方式使用 OUTPUT 子句:

BULK INSERTOrders table 并将 BULK INSERT 中的所有 Id's 存储到 table 变量中。 之后,将详细信息插入 OrderDetail,从已经存储它们的 table 变量中获取 OrderId

您可以查看此代码的工作演示 here

     DECLARE @outputtbl TABLE ( id INT );
     --here you will store the bulk inserted id's 
     --here you will do the bulk insert (note that i used a union all of several      
         selects as a "source" for your bulk insert)
     INSERT INTO Orders
     OUTPUT inserted.id
            INTO @outputtbl ( id )
     SELECT *
     FROM   ( SELECT    1 AS id ,
                        GETDATE() AS dt
              UNION ALL
              SELECT    2 AS id ,
                        GETDATE() AS dt
              UNION ALL
              SELECT    3 AS id ,
                        GETDATE() AS dt
              UNION ALL
              SELECT    4 AS id ,
                        GETDATE() AS dt
            ) t;

     --inserting into OrderDetail, OrderId's from the table variable and other fields as per your logic. (`item name` here it's just an example)
     INSERT INTO OrderDetail
            ( orderid, itemname )
     SELECT id ,
            'itemx'
     FROM   @outputtbl;

我创建了两个简单的 tables OrdersOrderDetail 来模拟问题。

这只是一个示例 table,我正在 table

中插入大量示例数据
DECLARE @Counter INT 
SET @Counter = 1
    WHILE @Counter < 50000
        BEGIN 
         INSERT [SampleTableName] VALUES(Id)
            SELECT 
                NEWID() -- i have a column sample_id so i am entrying random 
                newid() into that
                ABS (CHECKSUM(NEWID())) % 60 + 1,
                DATEADD ( DAY, ABS(CHECKSUM(NEWID()) % 3650), '2007-04-01')
                -- i have a sample date field as well and i am entrying 10 
                   years of date in that
            SET @Counter += 1
        END