使用存储过程将批量数据插入主/详细信息表的最佳方法?

时间:2017-04-24 07:39:19

标签: sql-server tsql stored-procedures master-detail

假设我有一个名为订单的主表和名为 OrderDetail 的详细信息表,OrderId是身份密钥并在{{1}中使用作为外键。现在我希望将带有存储过程的 批量数据 插入OrderDetail,然后将相关详细信息插入Order表。 谁能告诉我最好的方法呢?如何从master和我使用的详细信息表中获取标识值?

2 个答案:

答案 0 :(得分:1)

您可以使用OUTPUT子句,如下所示:

BULK INSERTOrders表并将Id's中的所有BULK INSERT存储到表变量中。 之后,将详细信息插入OrderDetail,从已存储它们的表变量中获取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;

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

答案 1 :(得分:1)

这只是一个示例表,我在表格中插入大量样本数据

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