Mic*_*per 1 sql sql-server bulkinsert
我使用sp_xml_preparedocument进行批量插入.但是我想在父表中进行批量插入,为每个新插入的行获取scope_identity,然后在子表中进行批量插入.
我可以通过在过程中为父表获取表变量并在该表中插入我应该在父表中插入的数据来完成此操作.现在循环遍历游标中的每一行,插入实际表中,然后插入子表中.
但是有没有光标的击球方式?我想要一些最佳解决方案
如果您使用的是SQL Server 2008或更高版本,则可以按照此问题中的说明使用合并.
创建一个表变量,该变量将在执行合并时从父表中捕获生成的id以及子XML Parent.然后Child从表变量插入.
注意:我使用XML数据类型而不是openxml.
表:
create table Parent
(
ParentID int identity primary key,
Name varchar(10) not null
);
create table Child
(
ChildID int identity primary key,
Name varchar(10) not null,
ParentID int not null references Parent(ParentID)
);
Run Code Online (Sandbox Code Playgroud)
XML:
<root>
<parent>
<name>parent 1</name>
<child>
<name>child 1</name>
</child>
<child>
<name>child 2</name>
</child>
</parent>
<parent>
<name>parent 2</name>
<child>
<name>child 3</name>
</child>
</parent>
</root>
Run Code Online (Sandbox Code Playgroud)
码:
declare @Child table
(
ParentID int primary key,
Child xml
);
merge Parent as P
using (
select T.X.value('(name/text())[1]', 'varchar(10)') as Name,
T.X.query('child') as Child
from @XML.nodes('/root/parent') as T(X)
) as X
on 0 = 1
when not matched then
insert (Name) values (X.Name)
output inserted.ParentID, X.Child into @Child;
insert into Child(Name, ParentID)
select T.X.value('(name/text())[1]', 'varchar(max)'),
C.ParentID
from @Child as C
cross apply C.Child.nodes('/child') as T(X);
Run Code Online (Sandbox Code Playgroud)