我正在将XML文档导入SQL表。它是嵌套的xml。我需要做3张桌子。我决定使用游标。我在第一个光标的主节点上一行一行地查找。它完美地添加到第一个表中。将其添加到表后我想只使用另一个游标访问FROM OPENXML语句中的某些节点子节点。到目前为止,我设法读取每个子节点数据,而不仅仅是我感兴趣的一个。你能告诉我如何只进入我用第一个光标读取的那个cerain父节点的子节点吗?
<root>
<mainnode>
<name>Main node 1</name>
<children>
<childrenname>Children name1</childrenname>
</children>
<children>
<childrenname>Children name2</childrenname>
</children>
</mainnode>
<mainnode>
<name>Main node 2</name>
<children>
<childrenname>Children name3</childrenname>
</children>
<children>
<childrenname>Children name4</childrenname>
</children>
</mainnode>
</root>
让我们说这是我的数据XML结构。我通过批量函数添加它。我现在做的是
DECLARE @name varchar(400),
DECLARE kursor CURSOR LOCAL FORWARD_ONLY FOR SELECT name from OPENXML(@DocID, 'root/mainnode', 2)
WITH name
open kursor
FETCH NEXT FROM kursor into @name
WHILE @@FETCH_STATUS = 0
BEGIN
--here i am adding record to first table, one by one with some insert
--and also here i need to reach children elements, but only of that certain mainnode
-- thats also the place to add second kursor
DECLARE childrenname varchar(400),
DECLARE kursorchildren CURSOR LOCAL FORWARD_ONLY FOR SELECT childrenname from OPENXML(@DocID, 'root/mainnode/children', 2)
WITH childrenname
OPEN kursorchildren
FETCH NEXT FROM kursorchildren into @childrenname
WHILE @@FETCH_STATUS = 0
BEGIN
--here i want to insert into table again, but only that childrens that are from actual row, not every form document.
FETCH NEXT FROM kursorchildren into @childrenname
END
CLOSE kursorchildren
DEALLOCATE kursorchildren
FETCH NEXT FROM kursor into @name
END
CLOSE kursorClaimsMain
DEALLOCATE kursorClaimsMain
答案 0 :(得分:0)
尝试将其选择为普通表格,如下所示:
declare @xml xml = N'<root>
<mainnode>
<name>Main node 1</name>
<children>
<childrenname>Children name1</childrenname>
</children>
<children>
<childrenname>Children name2</childrenname>
</children>
</mainnode>
<mainnode>
<name>Main node 2</name>
<children>
<childrenname>Children name3</childrenname>
</children>
<children>
<childrenname>Children name4</childrenname>
</children>
</mainnode>
</root>'
select
t.value('.','nvarchar(max)') as children_name
,t.value('(../name)[1]','nvarchar(max)') as node_name
,t.value('for $a in .. return 1+count($a/../*[. << $a])', 'int') as code_id
from @xml.nodes('root/mainnode/children') t(t)
您将获得每个主要代码和儿童列表的身份。因此,您可以提取到任何您想要的表格。