Cursor for spliting t-sql @xml variable on elements level

亡梦爱人 提交于 2021-02-10 23:43:29

问题


I need to define some cursor for spliting t-sql @xml variable on elements level into different @xml(s).

for example:

<root>
<element id=10/>
<element id=11/>
<element id=12/>
<element id=13/>
</root>

so that get the following values inside of tsql cursor:

<root><element id=10/><element id=11/></root>

then

<root><element id=12/><element id=13/></root>

and so on where n number of elements pro cursor loop.


回答1:


Well, you can use the build-in functions for manipulating XML. For example, the following statement:

DECLARE @XML XML = N'<root><element id="10"/><element id="11"/><element id="12"/><element id="13"/></root>'

SELECT  ROW_NUMBER() OVER (ORDER BY T.c) 
       ,T.c.query('.')
FROM @XML.nodes('root/element') T(c)

will give you all elements preserving the order they have in the XML structure:

enter image description here

Then you can stored this result and build separate smaller XML variables.


For different elements you can use * like this:

DECLARE @XML XML = N'<root><element1 id="10"/><element2 id="11"/><element3 id="12"/><element4 id="13"/></root>'

SELECT  ROW_NUMBER() OVER (ORDER BY T.c) 
       ,T.c.query('.')
FROM @XML.nodes('root/*') T(c)

enter image description here



来源:https://stackoverflow.com/questions/28882973/cursor-for-spliting-t-sql-xml-variable-on-elements-level

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