使用SQL将键值对表数据转换为XML

时间:2018-01-24 12:55:59

标签: xml tsql pivot

我有一个以下形状的表

RecordID      KeyText      ValueText
--------      -------      ---------
1             "A Key 1"    "Some text for A Key 1"
1             "A Key 2"    "Some text for A Key 2"
2             "A Key 1"    "Some text for A Key 1"
.....

任何给定的RecordID(它是主记录的外键)都可以在此表中包含一行或多行。

我想将这些记录分组为每个RecordID的单个记录,并使用以下格式的XML类型字段

RecordID: 1
<LegacyDataItem>
    <Field Key="A Key 1" Value="Some text for A Key 1" />
    <Field Key="A Key 2" Value="Some text for A Key 2" />
</LegacyDataItem>

RecordID:2
<LegacyDataItem>
    <Field Key="A Key 1" Value="Some text for A Key 1" />
</LegacyDataItem>

.....

如何使用SQL输出XML?

1 个答案:

答案 0 :(得分:0)

试试这样:

DECLARE @mockupTable TABLE(RecordID INT,KeyText VARCHAR(100),ValueText VARCHAR(100));
INSERT INTO @mockupTable VALUES
 (1,'A Key 1','Some text for A Key 1')
,(1,'A Key 2','Some text for A Key 2')
,(2,'A Key 1','Some text for A Key 1');

SELECT RecordID 
      ,(
        SELECT m2.KeyText AS [@Key]
              ,m2.ValueText AS [@Value]
        FROM @mockupTable AS m2
        WHERE m2.RecordID=m.RecordID
        FOR XML PATH('Field'),ROOT('LegacyDataItem'),TYPE
       )
FROM @mockupTable AS m
GROUP BY RecordID;

结果:

RecordID    XML
1           <LegacyDataItem><Field Key="A Key 1" Value="Some text for A Key 1" /><Field Key="A Key 2" Value="Some text for A Key 2" /></LegacyDataItem>
2           <LegacyDataItem><Field Key="A Key 1" Value="Some text for A Key 1" /></LegacyDataItem>

外部选择将按RecordID分组,子选择查找相关记录并将其作为XML返回

相关问题