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

时间:2008-08-05 20:35:56

标签: sql xml sql-server-2005 formatting for-xml

我有一个表格,其结构如下:

------------------------------
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

到目前为止,我已经查看了the MSDN page上的文档,但是我没有得到预期的结果。


@KG,

你实际上给了我这个输出:

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

我现在要坚持使用Chris Leon的FOR XML EXPLICIT

5 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分:0)

试试这个,克里斯:

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

可怕的抱歉!我混淆了你要求的东西。我更喜欢XML AUTO只是为了便于维护,但我相信其中任何一个都是有效的。我为疏忽道歉; - )

答案 2 :(得分:0)

我明白了:

select
1 as tag,
null as parent,
AccountNumber as 'root!1!clientID!element'
from
Location.LocationMDAccount
where
locationid = 'long-guid-here'
for xml explicit

答案 3 :(得分:0)

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')

答案 4 :(得分:0)

使用SQL Server 2005(或者可能是2008)我发现XML PATH允许更容易维护SQL而不是XML Explicit(特别是一旦SQL更长)。

在这种情况下:

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