日期:2014-05-17  浏览次数:20456 次

sql : xml 获取数据集
表中有一个字段是xml,xml的格式如下:
<root>
   <item>
     <name>名称A</name>
     <type> 内容类型为1</type>
     <attr>{当contentType值为1时有值}A</attr>
     <field> {当contentType值为2时有值}B</field>
   </item >
   <item>
     <name>名称B</name>
     <type> 内容类型为2</type>
     <attr>{当contentType值为1时有值}C</attr>
     <field> {当contentType值为2时有值}D</field>
   </item>
</root>

我需要一条查询语句能以表的形式显示数据集
id  name     type    attr     field 
1  名称A      1       A        NULL
2  名称B      2       NULL      D
这个SQL语句要如何写
SQL XML xquery

------解决方案--------------------
declare @t table(col xml)
insert @t select '<root>
   <item>
     <name>A</name>
     <type> 1</type>
     <attr>A</attr>
     <field> B</field>
   </item >
   <item>
     <name>B</name>
     <type> 2</type>
     <attr>C</attr>
     <field>D</field>
   </item>
</root>'

select 
b.c.value('(name/text())[1]','varchar(50)')name
,b.c.value('(type/text())[1]','varchar(50)')type
,case when b.c.exist('type[text()=1]')=1 then b.c.value('(attr/text())[1]','varchar(50)') end  attr
,case when b.c.exist('type[text()=2]')=1 then b.c.value('(field/text())[1]','varchar(50)') end field
from @t as a
cross apply a.col.nodes('root/item') as b(c)

/*
name type attr field
A  1 A NULL
B  2 NULL D
*/

------解决方案--------------------
OPENXML
http://technet.microsoft.com/zh-cn/ms175160.aspx