1

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
4

1 回答 1

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
于 2013-07-04T11:06:58.450 回答