我必须将多个记录插入表中,并将第一个表的标识列插入另一个表所需的平均时间。我可以避免循环吗?
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.
答案 0 :(得分:1)
您可以使用OUTPUT
clause将INSERT
操作中的多个列/行输出到表变量中。
假设您要插入的表格中有一个名为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
值,以便您可以根据该信息进行第二次插入。