繁体   English   中英

如何获取SQL以生成开始和结束XML标签

[英]How do I get SQL to generate both the starting and ending XML tags

当值是NULL时,我需要在SQL中将开始和结束XML标记呈现为<PropName></PropName> NOT <PropName />

我知道这不是标准,但是我有商业理由要这样做。 我尝试了FOR XML PATH ('')语句的几种变体,但似乎无法使其呈现为<PropName></PropName>

select [PropName] as '*' for xml path(''), type) as [PropName]

renders <PropName />如何更改为呈现为<PropName></PropName>

感谢大家的反馈。 我知道“ <” PropName“>”“ <” / PropName“>”和“ <” PropName /“>”是100%相同的东西,我知道无论需要它的人都应该将其修复。 生成的文件被发送给第三方供应商,他们坚持将其呈现为。 幸运的是,一个同事确定了我只需要在外部SELECT语句的末尾添加“,TYPE”,而不是在PropName所在的子选择中,然后就可以了-谁会猜到呢? 我想我应该提到我的PropName在子选择中。 也许那将有助于答案。

您已经找到了解决方案。 只是为了了解一下...

当然,诸如“更改阅读器而不是XML”之类的所有语句都是正确的。 但是有时我们必须满足我们无法更改的第三方要求。

有一些技巧可以处理空XML元素的生成。 将其粘贴到一个空的查询窗口中并执行。 检查结果...

--The NULL-element is not there at all
SELECT 'text' AS filled
      ,'' AS empty
      ,NULL AS NotThere
FOR XML PATH('row');   

--The NULL-element is rendered using "nil"
SELECT 'text' AS filled
      ,'' AS empty
      ,NULL AS NotThere
FOR XML PATH('row'),ELEMENTS XSINIL    

--Look at this: Both columns are called "TheName". They are implicitly concatenated
SELECT 'a' AS TheName
      ,'b' AS TheName
FOR XML PATH('row')

--That leads to: Concatenate nothing with an empty string will at least return the empty string.
--this is other/better than ISNULL, because it will work with any type...
SELECT NULL AS TheName
      ,'' AS TheName
FOR XML PATH('row')

DECLARE @tbl TABLE(int1 INT, int2 INT);
INSERT INTO @tbl VALUES(NULL,1);

--int1 is missing
SELECT *
FROM @tbl
FOR XML PATH('row');  

--both elements are there
SELECT int1, '' AS int1 --ISNULL(int1,'') would not compile...
      ,int2, '' AS int2
FROM @tbl
FOR XML PATH('row');

最后,如果确实需要这种转换,则可以创建XML,将其转换为VARCHAR并使用Replace将所有<PropName />更改为<PropName></PropName> 我现在必须洗手;-)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM