在SQL中插入多个记录并更新标识列

时间:2013-08-17 07:55:58

标签: sql-server-2008-r2

我必须将多个记录插入表中,并将第一个表的标识列插入另一个表所需的平均时间。我可以避免循环吗?

被修改

   i have two tables named StudentMaster and StudentSujects.

  First Table structure is (StudentID int Identity(1,1),StudentName varchar(100))

  Second table structure is (SubjectID int Identity(1,1),StudentID int,SubjectName varchar(100)).

'StudentSujects'表中的StudentID是第一个表'StudentMaster'的标识列。

INSERT INTO StudentMaster
                            (
                                 StudentName
                            )
                    SELECT       StudentName
                    FROM OPENXML(@hDoc,'/XML/Students')
                    WITH(    StudentName    varchar(100)    'StudentName')


   I am inserting multiple records in to the first table using the above query.I the mean time i have to insert the identity column of each row in to the second table.

1 个答案:

答案 0 :(得分:1)

您可以使用OUTPUT clauseINSERT操作中的多个列/行输出到表变量中。

假设您要插入的表格中有一个名为IDENTITY的{​​{1}}列,您可以使用以下代码:

ID

当然,您需要某些,它允许您识别第二个表中哪一行插入哪个值 - 这完全取决于您的情况(并且您没有提供任何解释在你的问题中。)

但基本上,使用DECLARE @InsertedData TABLE (NewID INT, SomeOtherColumn.....) INSERT INTO dbo.YourTable(Col1, Col2, ..., ColN) OUTPUT INTO @InsertedData(NewID, SomeOtherColumn) Inserted.ID, Inserted.OtherColumn VALUES(Val11, Val12, ..., Val1N), (Val21, Val22, ..., Val2N), .... (ValM1, ValM2, ..., ValMN) 子句,您可以根据需要捕获尽可能多的信息,包括新分配的OUTPUT值,以便您可以根据该信息进行第二次插入。