0

我有以下 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
4

1 回答 1

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)
于 2013-05-07T19:34:26.577 回答