我有xml以下,想要将所有记录作为行获取。我的xml如下所示..
<category ccode="ct8">
<columns>
<col colcode="cl_prodn" displaytext="Prodname" responsetype="textbox" tooltip="testts" isrequired="" displayorder="1" />
<col colcode="cl_descs" displaytext="Descs" responsetype="textarea" tooltip="atser" isrequired="on" displayorder="2" />
</columns>
</category>
我想要两行ccode = ct8。这两行将显示所有属性。我正在尝试下面的查询,但它只返回一个和第一个。
select CatConfig.value('(category/columns/col/@colcode)[1]', 'varchar(50)') from categories where CategoryId = 8
答案 0 :(得分:1)
有许多方法可以粉碎xml,但我相信这可能会帮助你提供更多的概念:
declare @xml xml =
'<category ccode="ct8">
<columns>
<col colcode="cl_prodn" displaytext="Prodname" responsetype="textbox" tooltip="testts" isrequired="" displayorder="1" />
<col colcode="cl_descs" displaytext="Descs" responsetype="textarea" tooltip="atser" isrequired="on" displayorder="2" />
</columns>
</category>'
-- get them one at a time by hunting for specific identifier
select @xml.query('(category/columns/col[@displaytext = "Prodname"])') -- queries for node
select @xml.value('(category/columns/col[@displaytext = "Prodname"]/@colcode)[1]', 'varchar(max)') -- gives value of node by description
select @xml.value('(category/columns/col[@displaytext = "Descs"]/@colcode)[1]', 'varchar(max)')
-- get them all at once with the (reference).(column).nodes method applied to an xml value in a table.
declare @X table ( x xml);
insert into @X values (@xml)
select
t.query('.')
, t.value('(@colcode)[1]', 'varchar(max)')
from @X a
cross apply a.x.nodes('//category/columns/col') as n(t)