我有一个包含以下数据的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 & 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服务器表。但是因为一个ITEM有多个类别。那么我该如何处理这个XML。
我的意思是我想将DATA转移到两个表
在tableA中每个记录一行,例如:
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 & 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)
答案 0 :(得分:1)
您可以两次应用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)