Skip to content
Advertisement

sql xml with nested node

I have a below table in MS sql server 2012

I need the below xml format :

I have the sample query but it is not working for multiple columns :

Advertisement

Answer

SQL XML generation is a bit weird. If you need to have two elements of the same name following each other you need to separate them with a null valued column, e.g.:

Which yields…

=====

Second answer to match the second version of the question…

I’d be querying your designer about the requirements of the new XML. There’s now no relationship between the elements containing emp_ID and emp_dept attributes. Previously they were siblings grouped together inside the staticData parent elements, now they are in separate parents and can be ordered independently according to the whims of SQL Server.

To generate your new XML format requires subqueries to populate the children of the staticData and DynData elements, e.g.:

Which yields…

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement