如果不是空的话,在XML输出中包含字段,在空的时候省略

时间:2015-02-27 13:38:47

标签: sql xml sql-server-2008

我的第一个问题,但我一直在阅读并从这个伟大的网站上学到很多东西。 简短介绍,我是一家全球性公司的应用支持专家。 11月开始,但已经淹没了工作。

目前,我正致力于从我们的SQL Server环境创建XML文件,以宣布我们的货物运往匈牙利海关。在Stackoverflow线程的帮助下,它已经全部正常工作了。 现在我正在调整职责,我正在努力解决以下问题。

在XML中,有些可选字段有时会填充,但并非总是如此。麻烦的是,当字段为空时,XML将失败。因此,当为空时,不应包括完整标记。当字段填满时,标记和数据应包含在XML文件中。

实施例

 SELECT    [LocationName] as name
          ,[LocationPhone] as phone
          ,[LocationEmail] as email
          ,[LocationCountry] as country
          ,[LocationCity] as city
    FROM [XML_view]
    FOR XML PATH ('Location'), ELEMENTS, TYPE

姓名,国家和城市是强制性的,并且始终填写,但电话和电子邮件可能为空,也可能不为空。

结果现在如下;

<Location 
  <name>BuildingOne</name>
  <phone />
  <email />
  <country>NL</country>
  <city>Amsterdam</city>
</Location>

但我希望手机和电子邮件在空白时不在XML中。

我尝试使用IF EXISTS和IF NOT NULL,但这不起作用。 有人有任何建议吗?

1 个答案:

答案 0 :(得分:2)

我的猜测是你有空字符串而不是NULL值。这显示了差异;

;with cte as (
select 'John' as [LocationName], '0123456789' as [LocationPhone], 'john@smith.com' as [LocationEmail],'UK' as [LocationCountry],'London' as [LocationCity]
union all
select 'Peter' as [LocationName], '' as [LocationPhone], '' as [LocationEmail],'UK' as [LocationCountry],'Sheffield' as [LocationCity]
union all
select 'Sally' as [LocationName], null as [LocationPhone], null as [LocationEmail],'UK' as [LocationCountry],'Reading' as [LocationCity]
)
 SELECT    [LocationName] as name
          ,[LocationPhone] as phone
          ,[LocationEmail] as email
          ,[LocationCountry] as country
          ,[LocationCity] as city
    FROM cte
    FOR XML PATH ('Location'), ELEMENTS, TYPE

您可以使用NULLIF将空字符串更改为NULL,它们将从XML中消失;

;with cte as (
select 'John' as [LocationName], '0123456789' as [LocationPhone], 'john@smith.com' as [LocationEmail],'UK' as [LocationCountry],'London' as [LocationCity]
union all
select 'Peter' as [LocationName], '' as [LocationPhone], '' as [LocationEmail],'UK' as [LocationCountry],'Sheffield' as [LocationCity]
union all
select 'Sally' as [LocationName], null as [LocationPhone], null as [LocationEmail],'UK' as [LocationCountry],'Reading' as [LocationCity]
)
 SELECT    nullif([LocationName], '') as name
          ,nullif([LocationPhone], '') as phone
          ,nullif([LocationEmail], '') as email
          ,nullif([LocationCountry], '') as country
          ,nullif([LocationCity], '') as city
    FROM cte
    FOR XML PATH ('Location'), ELEMENTS, TYPE