正确格式化sql会产生预期的xml输出

时间:2015-05-15 13:59:26

标签: sql-server xml for-xml for-xml-path

感谢SO用户,我正在使用FOR XML取得进展,但我显然没有完全正确地使用sql语法。

假设我有以下sql

DECLARE @Uname VARCHAR(15) = 'Dom',
        @Pword VARCHAR(15) = 'Monty'

SELECT 
   RTRIM(@Uname) AS '@uname',
   RTRIM( @Pword) AS '@pword',
   (SELECT COALESCE(PortOfLanding,'') AS portOfLanding 
    FROM Landings.LandingHeaders  
    WHERE Posted = 0 
    FOR XML PATH('Sale')) 
FOR XML PATH('abc')

运行时会产生以下输出

<abc uname="Dom" pword="Monty">&lt;Sale&gt;&lt;portOfLanding&gt;GBHTG&lt;/portOfLanding&gt;&lt;/Sale&gt;&lt;Sale&gt;&lt;portOfLanding&gt;GBHTG&lt;/portOfLanding&gt;&lt;/Sale&gt;</abc>

我真正希望的是以下

<abc uname="Dom" pword="Python">
    <Sale portOfLanding= "GBHTG" />
    <Sale portOfLanding= "GBHTG"/>
</abc>

实际上我想在SQL中添加第三部分,以便最终可能最终得到像这样的xml

<abc uname="Dom" pword="Python">
    <Sale portOfLanding= "GBHTG">
        <saleline detail="some value here" />
        <saleline detail="some value here" />
    <Sale/>
    <Salesnote portOfLanding= "GBHTG"/>
</abc>

有人可以指出我在原始SQL查询中出错的地方吗?

由于

1 个答案:

答案 0 :(得分:1)

试试这个:

DECLARE @Uname VARCHAR(15) = 'Dom',
        @Pword VARCHAR(15) = 'Monty';

SELECT RTRIM(@Uname) AS '@uname',
       RTRIM( @Pword) AS '@pword', 
      (SELECT COALESCE(PortOfLanding,'') AS '@portOfLanding' 
       FROM Landings.LandingHeaders  
       WHERE Posted = 0 
       FOR XML PATH('Sale'), TYPE)
FOR XML PATH('abc')

你可以更深入地了解:

SELECT RTRIM(@Uname) AS '@uname',
       RTRIM( @Pword) AS '@pword', 
      (SELECT COALESCE(PortOfLanding,'') AS '@portOfLanding',
             (SELECT COALESCE(PortOfLanding,'') AS '@detail'
              FROM Landings.LandingHeaders  
              FOR XML PATH('SaleLine'), TYPE)
       FROM Landings.LandingHeaders  
       WHERE Posted = 0 
       FOR XML PATH('Sale'), TYPE)
FOR XML PATH('abc')