SQL Server 2008R2或2012
是否可以将XML节点查询作为单行而不是多行返回,其中每个返回的项目是新列而不是行?
例如,XML字段包含以下XML结构:
<MetaFieldData>
<MetaField>
<Name>Volume</Name>
<Value>Large</Value>
</MetaField>
<MetaField>
<Name>Code</Name>
<Value>3DP</Value>
</MetaField>
<MetaField>
<Name>Photo</Name>
<Value>foo.png</Value>
</MetaField>
<MetaField>
<Name>CommonName</Name>
<Value>Foo Bar</Value>
</MetaField>
</MetaFieldData>
使用以下SQL:
select
m.value('Name[1]', 'varchar(100)') as Name,
m.value('Value[1]', 'varchar(max)') as Value
from MyTable
cross apply MetaFieldData.nodes('/MetaFieldData/MetaField') as Meta(m)
where Id = 1
结果集将返回:
Name Value
--------------------
Volume Large
Code 3DP
Photo foo.png
CommonName Foo Bar
如何将结果集返回为:
Volume Code Photo CommonName
----------------------------------------------
Large 3DP foo.png Foo Bar
答案 0 :(得分:0)
试试这个
SELECT Volume,Code,Photo,CommonName
FROM
(
SELECT
m.value('Name[1]', 'varchar(100)') as Name,
m.value('Value[1]', 'varchar(max)') as Value
FROM MyTable
CROSS APPLY MetaFieldData.nodes('/MetaFieldData/MetaField') as Meta(m)
WHERE Id = 1
) P
PIVOT
(
MAX(Value) FOR Name IN (Volume,Code,Photo,CommonName)
) pvt