【问题标题】:Inserting batch of rows into two tables in SQL Server 2008在 SQL Server 2008 中将一批行插入到两个表中
【发布时间】:2011-09-02 13:26:28
【问题描述】:

我需要在table1 中插入多行,同时在table2 中插入一行,其中pkID 来自table1 和一个来自SP 参数的值。

我创建了一个存储过程,它使用表值参数执行批量插入,其中包含要插入到table1 中的行。但是我在将行插入table2 时遇到问题,该行具有来自table1 的相应Id(身份)以及我传递的参数值。

有没有人实现了这个,或者有什么好的解决方案?

CREATE PROCEDURE [dbo].[oSP_TV_Insert]
  @uID int
  ,@IsActive int
  ,@Type int -- i need to insert this in table 2
  ,@dTableGroup table1  READONLY -- this one is a table valued
AS

DECLARE @SQL varchar(2000)
DECLARE @table1Id int
 BEGIN

    INSERT INTO dbo.table1  
        (uID
        ,Name
        ,Contact
        ,Address
        ,City
        ,State
        ,Zip
        ,Phone
        ,Active)  
    SELECT 
        @uID  
        ,Name
        ,Contact
        ,Address
        ,City
        ,State
        ,Zip
        ,Phone
        ,Active
        ,@G_Active   
    FROM @dTableGroup
--the above query will perform batch insert using the records from dTableGroup which is table valued

SET @table1ID = SCOPE_IDENTITY()

-- this below will perform inserting records to table2 with every Id inserted in table1.

Insert into table2(@table1ID , @type)

【问题讨论】:

标签: sql-server


【解决方案1】:

您需要临时存储插入的标识值,然后使用 OUTPUT 子句创建第二个 INSERT 语句。

类似:

-- declare table variable to hold the ID's that are being inserted
DECLARE @InsertedIDs TABLE (ID INT)

-- insert values into table1 - output the inserted ID's into @InsertedIDs
INSERT INTO dbo.table1(ID, Name, Contact, Address, City, State, Zip, Phone, Active)  
     OUTPUT INSERTED.ID INTO @InsertedIDs
     SELECT 
         @ID, Name, Contact, Address, City, State, Zip, Phone, Active, @G_Active   
    FROM @dTableGroup

然后你可以有你的第二个 INSERT 语句:

INSERT INTO dbo.table2(Table1ID, Type)
    SELECT ID, @type FROM @InsertedIDs

请参阅MSDN docs on the OUTPUT clause 了解更多关于您可以使用 OUTPUT 子句执行哪些操作的详细信息 - 这是 SQL Server 当今最未被充分利用和最“未知”的功能之一!

【讨论】:

    【解决方案2】:

    由于您需要所有插入的标识值,请查看插入语句的输出子句:http://msdn.microsoft.com/en-us/library/ms177564.aspx

    【讨论】:

    • 我认为这里得到的 scope_identity 是最后一个?第一个呢?
    • 您的身份列的名称是什么?它看起来不像是 ID,因为您在存储过程插入语句中提供了一个值。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-09
    • 2012-03-24
    • 1970-01-01
    • 1970-01-01
    • 2011-05-22
    • 1970-01-01
    相关资源
    最近更新 更多