如何在案情中形成XML节点

时间:2019-02-03 18:06:57

标签: sql sql-server xml

SQL查询

SELECT
    (CASE
        WHEN a.ClubNumber IS NULL OR a.ClubNumber = ''
           THEN ''
           ELSE (b.cityname + b.statename + 
                 RTRIM(CAST(b.zipcodevalue AS VARCHAR(10))) + b.countryname)
     END) AS 'billing_info'
FROM 
    dbo.CustomerList a 
LEFT JOIN
    [dbo].[Subscribptions] c on RTRIM(a.LocationID) = c.LocationId
FOR XML PATH('subscription'), ROOT('subscriptions')

这没有错误。

但是我需要的是当ClubNumber不为Null时,我需要如下所示的XML节点。

SELECT
    (CASE
        WHEN a.ClubNumber IS NULL OR a.ClubNumber = ''
           THEN ''
           ELSE (b.cityname AS 'account/billing_info/city',
                 b.statename AS 'account/billing_info/state',
                 RTRIM(CAST(b.zipcodevalue AS VARCHAR(10))) AS 'account/billing_info/zip',
                 b.countryname as 'account/billing_info/country'
FROM 
    dbo.CustomerList a 
LEFT JOIN
    [dbo].[Subscribptions] c on RTRIM(a.LocationID) = c.LocationId
FOR XML PATH('subscription'), ROOT('subscriptions')

但这会引发语法错误。

如何如上所述设置列XML节点的格式?

谢谢!

1 个答案:

答案 0 :(得分:0)

您可以使用子选择FOR XML ... TYPE。这样,子选择的部分XML可以用作外部查询中XML的一部分。

...
CASE
  WHEN a.clubnumber IS NULL
        OR a.clubnumber = '' THEN
    ''
  ELSE
    (SELECT b.cityname "account/billing_info/city",
            b.statename "account/billing_info/state",
            rtrim(cast(b.zipcodevalue AS varchar(10))) "account/billing_info/zip",
            b.countryname "account/billing_info/country"
            FOR XML PATH(''),
                    TYPE)
END
...