将 XML 数据解析为 SQL 具有多个子节点数据

Parse XML data to SQL with multiple child node data

我有一个 xml 文件,其中包含以下数据

<SearchProgramsResponse xmlns="http://api.abc.com/2011-03-01/">
<page>1</page>
<items>50</items>
<total>3129</total>
<programItems>
<programItem id="7779">
<name>Coolblue NL</name>
<adrank>5.4</adrank>
<categories>
<category id="40">Cell, Phone &amp; Fax</category>
<category id="11">Internet services</category>
</categories>
</programItem>


<programItem id="7780">
<name>ABC NL</name>
<adrank>2.4</adrank>
<categories>
<category id="42">Cell</category>
<category id="12">services</category>
</categories>
</programItem>
</programItems>
</SearchProgramsResponse>

我想将此 XML 数据传输到 SQL 服务器表。但是由于一个项目有多个类别..所以我如何处理这个 XML.

我的意思是我想将DATA传输到两个表

在表A中,每条记录一行,例如:

TableA(ITEM) : programItem , Name , adrank 
TABLEB(Category) : ITEMID, categoryID ,CategoryName  

我已经查看了 XML 参考资料,但都是单值 xml 属性,我该如何处理这种类型的 XML?

我已经尝试了下面的两个查询,但都没有成功

DECLARE @xmldata XML 
SET @xmldata =
N'<SearchProgramsResponse xmlns="http://api.abc.com/2011-03-01/">
<page>1</page>
<items>50</items>
<total>3129</total>
<programItems>
<programItem id="7779">
<name>Coolblue NL</name>
<adrank>5.4</adrank>
<categories>
<category id="40">Cell, Phone &amp; Fax</category>
<category id="11">Internet services</category>
</categories>
</programItem>
<programItem id="7780">
<name>ABC NL</name>
<adrank>2.4</adrank>
<categories>
<category id="42">Cell</category>
<category id="12">services</category>
</categories>
</programItem>
</programItems>
</SearchProgramsResponse>';



SELECT  
       Tbl.Col.value('name[1]', 'varchar(70)')
FROM   @xmldata.nodes('/SearchProgramsResponse/programItems/programItem') Tbl(Col)  


SELECT
     XReservering.value('@programItem', 'int'),
     XOpties.value('(.)', 'varchar(50)')
FROM
    @xmldata.nodes('/SearchProgramsResponse/programItems/programItem') AS XTbl1(XReservering)
CROSS APPLY
    XReservering.nodes('categories/category') AS XTbl2(XOpties)

那么你可以应用 nodes() 函数两次来获取具有 item_id 的所有类别:

;with xmlnamespaces(default 'http://api.abc.com/2011-03-01/')
select
    t.c.value('@id', 'int') as id,
    t.c.value('(name/text())[1]', 'nvarchar(max)') as name,
    t.c.value('(adrank/text())[1]', 'decimal(29,10)') as adrank
from @data.nodes('SearchProgramsResponse/programItems/programItem') as t(c)

;with xmlnamespaces(default 'http://api.abc.com/2011-03-01/')
select
    t.c.value('@id', 'int') as item_id,
    c.c.value('@id', 'int') as category_id,
    c.c.value('text()[1]', 'nvarchar(max)') as category_name
from @data.nodes('SearchProgramsResponse/programItems/programItem') as t(c)
    outer apply t.c.nodes('categories/category') as c(c)