How to break up two xml tags with the same subchild names in SQL

﹥>﹥吖頭↗ 提交于 2019-12-22 17:42:18

问题


I have created a script which takes data from a table in SQL and generates an XML output. The parent, child and sub-child tags are all the same which for 2 tags. The SQL script is outputting them as one XML value instead of 2.

 SELECT
 Request.TransactionRef AS [RequestHeader/RequestID],
'Deal.Trial' AS [RequestHeader/Action],
'DoDealValidate' AS [RequestHeader/ActionFlags/Flag],
'DoDealDerive' AS [RequestHeader/ActionFlags/Flag] 

The current results are:

<ActionFlags>
<Flag>DoDealValidateDoDealDerive</Flag>
</ActionFlags>




<ActionFlags>
<Flag>DoDealValidate</Flag>
<Flag>DoDealDerive</Flag>
</ActionFlags>

回答1:


Just place something empty in between:

SELECT
 'blah' AS [RequestHeader/RequestID],
'Deal.Trial' AS [RequestHeader/Action],
'DoDealValidate' AS [RequestHeader/ActionFlags/Flag],
NULL AS [RequestHeader/ActionFlags],
'DoDealDerive' AS [RequestHeader/ActionFlags/Flag] 
FOR XML PATH('row');

The background:

The engine is running through the SELECT's columns and builds them one after the other.

  • Well, there is a <RequestHeader> to open
  • and there is a <RequestID> to open
  • Again the <RequestHeader>, still open, nothin to to
  • and there is <Action> below... Oh, we must close the <RequestID> and open a new <Action>
  • and so on...

In your code the <Flag> is still open, therefore the content is written into the open element.

My change will let the engine think

  • Ah, we move up one level, so we close the <Flag> first... Oops, there's nothing to write...
  • Now there is something for <Flag>, which is not open anymore, we have to re-open a (new) <Flag> node
  • and so on...


来源:https://stackoverflow.com/questions/57804930/how-to-break-up-two-xml-tags-with-the-same-subchild-names-in-sql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!