T-SQL生成XML

时间:2017-01-26 08:24:24

标签: sql-server xml tsql

我有一个包含以下结构的表

StreetNumber varchar(50)
Apartment varchar(50)
Floor varchar(50)

我想将数据转换为XML,如下所示:

<Attributes>
    <AddressAttribute ID="1">
        <AddressAttributeValue>
            <Value>3</Value>
        </AddressAttributeValue>
    </AddressAttribute>
    <AddressAttribute ID="3">
        <AddressAttributeValue>
            <Value>1</Value>
        </AddressAttributeValue>
    </AddressAttribute>
    <AddressAttribute ID="2">
        <AddressAttributeValue>
            <Value>2</Value>
        </AddressAttributeValue>
    </AddressAttribute>
</Attributes>

有没有办法将每列转换为具有相同名称的元素,并且仅与属性ID不同?

2 个答案:

答案 0 :(得分:4)

您可以在列列表中的子查询中创建XML,您可以在表格构造函数中取消忽略值,为每列提供ID。

以下是使用表变量作为数据源的示例。你当然应该使用你的表。

declare @T table
(
  StreetNumber varchar(50),
  Apartment varchar(50),
  Floor varchar(50)
);

insert into @T values('Street', 'Apartment', 'Floor');

select (
       select R.ID as '@ID',
              R.Value as 'AddressAttributeValue/Value'
       from (values(1, T.StreetNumber),
                   (2, T.Apartment),
                   (3, T.Floor)) as R(ID, Value)
       for xml path('AddressAttribute'), root ('Attributes'),  type
       )
from @T as T;

结果:

<Attributes>
  <AddressAttribute ID="1">
    <AddressAttributeValue>
      <Value>Street</Value>
    </AddressAttributeValue>
  </AddressAttribute>
  <AddressAttribute ID="2">
    <AddressAttributeValue>
      <Value>Apartment</Value>
    </AddressAttributeValue>
  </AddressAttribute>
  <AddressAttribute ID="3">
    <AddressAttributeValue>
      <Value>Floor</Value>
    </AddressAttributeValue>
  </AddressAttribute>
</Attributes>

答案 1 :(得分:1)

已经有一个已接受的答案,这很好。就像另一种选择......

简短说明:通常,引擎不允许在同一级别中将多个具有相同名称的元素放在同一级别中。但是它们之间的,''(空元素)告诉引擎关闭一个元素并开始一个新元素。

DECLARE @Addr TABLE(StreetNumber varchar(50),Apartment varchar(50),Floor varchar(50));
INSERT INTO @Addr VALUES('SomeStreet', 'App 1', 'Floor 2');

SELECT 1 AS [AddressAttribute/@ID]
      ,a.StreetNumber [AddressAttribute/AddressAttributeValue/Value]
      ,''
      ,2 AS [AddressAttribute/@ID]
      ,a.Apartment [AddressAttribute/AddressAttributeValue/Value]
      ,''
      ,3 AS [AddressAttribute/@ID]
      ,a.Floor AS [AddressAttribute/AddressAttributeValue/Value]
      ,''
FROM @Addr AS a      
FOR XML PATH(''),ROOT('Attributes');

结果

<Attributes>
  <AddressAttribute ID="1">
    <AddressAttributeValue>
      <Value>SomeStreet</Value>
    </AddressAttributeValue>
  </AddressAttribute>
  <AddressAttribute ID="2">
    <AddressAttributeValue>
      <Value>App 1</Value>
    </AddressAttributeValue>
  </AddressAttribute>
  <AddressAttribute ID="3">
    <AddressAttributeValue>
      <Value>Floor 2</Value>
    </AddressAttributeValue>
  </AddressAttribute>
</Attributes>