SQL 服务器合并 XML 中的元素,但应该是单独的元素

SQL Server merges elements in XML, but should be separate elements

我有以下查询:

SELECT TOP 1 'St. Kulakow 12' AS 'address',
             'P123' AS 'address'
FROM tab
FOR XML PATH ('ROOT')

它returns我合并了标签'address',但它应该是分开的。

我得到:

<ROOT>
  <address>St. Kulakow 12P123</address>
</ROOT>

但应该是:

<ROOT>
 <address>St. Kulakow 12</address>
 <address>P123</address>
</ROOT>

有没有办法把它分开?

这样做:

SELECT TOP 1 'St. Kulakow 12' AS 'address',
             NULL,
             'P123' AS 'address'
--FROM tab
FOR XML PATH ('ROOT')

SELECT TOP 1 'St. Kulakow 12' AS 'address',
             '',
             'P123' AS 'address'
--FROM tab
FOR XML PATH ('ROOT')

"empty element" 用作元素的一种断路器。

TT。你是对的 :) 但在下面的情况下它根本不起作用:

SELECT 'Warsaw' AS 'ADR/City',
       'WKPL' AS 'ADR/State',
       'St. Kulakow 12' AS 'ADR/address',
        NULL,
       'P123' AS 'ADR/address',
       '12345' AS 'ADR/Zip'
FOR XML PATH ('ROOT')

您将获得:

<ROOT>
  <ADR>
    <City>Warsaw</City>
    <State>WKPL</State>
    <address>St. Kulakow 12</address>
  </ADR>
  <ADR>
    <address>P123</address>
    <Zip>12345</Zip>
  </ADR>
</ROOT>

因此我们需要为您的解决方案添加别名:

SELECT 'Warsaw' AS 'ADR/City',
       'WKPL' AS 'ADR/State',
       'St. Kulakow 12' AS 'ADR/address',
        NULL AS 'ADR',
       'P123' AS 'ADR/address',
       '12345' AS 'ADR/Zip'
FOR XML PATH ('ROOT')

然后我们将得到:

<ROOT>
  <ADR>
    <City>Warsaw</City>
    <State>WKPL</State>
    <address>St. Kulakow 12</address>
    <address>P123</address>
    <Zip>12345</Zip>
  </ADR>
</ROOT>

感谢您的帮助:)

试试这个

Table 姓名:DemoAddress

Id | Address
------------
1  | aaaa
2  | bbbb
3  | cccc  

查询将是这样的

select 'address'=Address from DemoAddress FOR XML PATH (''),type,root('root')

然后我们得到

<root>
  <address> aaaa</address>
  <address> bbbb</address>
  <address> cccc</address>
</root>