SQL Server 2005 For XML显式-需要帮助格式化

Translate

我有一个结构如下的表:

------------------------------
LocationID     | AccountNumber
------------------------------
long-guid-here | 12345
long-guid-here | 54321

要传递到另一个存储过程,我需要XML如下所示:

<root> 
    <clientID>12345</clientID>
    <clientID>54321</clientID>
</root>

到目前为止,我能做的最好的事情就是这样:

<root clientID="10705"/>

我正在使用此SQL语句:

SELECT
    1 as tag,
    null as parent,
    AccountNumber as 'root!1!clientID'
FROM
    Location.LocationMDAccount
WHERE
    locationid = 'long-guid-here'
FOR XML EXPLICIT

到目前为止,我已经看过有关MSDN页面,但是我还没有得到理想的结果。


@公斤,

您的输出实际上给了我:

<root>
  <Location.LocationMDAccount>
    <clientId>10705</clientId>
  </Location.LocationMDAccount>
</root>

我要坚持FOR XML EXPLICIT现在是Chris Leon的作品。

This question and all comments follow the "Attribution Required."

所有的回答

Translate

尝试

SELECT
    1 AS Tag,
    0 AS Parent,
    AccountNumber AS [Root!1!AccountNumber!element]
FROM
    Location.LocationMDAccount
WHERE
    LocationID = 'long-guid-here'
FOR XML EXPLICIT
来源
Translate

克里斯,试试看:

SELECT
    AccountNumber as [clientId]
FROM
    Location.Location root
WHERE
    LocationId = 'long-guid-here'
FOR
    XML AUTO, ELEMENTS

非常抱歉!我混了你的要求。我更喜欢XML AUTO只是为了易于维护,但是我相信任何一个都是有效的。我对监督表示歉意;-)

来源
Translate

我发现使用SQL Server 2005(或者大概是2008)比使用XML Explicit(尤其是一旦SQL更长)使XML PATH的维护变得容易得多。

在这种情况下:

SELECT AccountNumber as "clientID"
FROM Location.LocationMDAccount
WHERE locationid = 'long-guid-here'
FOR XML PATH (''), Root ('root');
来源
Translate

我得到了:

select
1 as tag,
null as parent,
AccountNumber as 'root!1!clientID!element'
from
Location.LocationMDAccount
where
locationid = 'long-guid-here'
for xml explicit
来源
Translate
SELECT 1             as tag,
       null          as parent,
       AccountNumber as 'clientID!1!!element'
FROM Location.LocationMDAccount
WHERE locationid = 'long-guid-here'
FOR XML EXPLICIT, root('root')
来源