Search code examples
sql-serverxmlsql-server-2008concatenation

Concatenate XML without type casting to string


I have the following XML generated from various tables in my SQL SERVER database

<XMLData>
...
<Type>1</Type>
...
</XMLData>

AND

<XMLData>
...
<Type>2</Type>
...
</XMLData>

AND

<XMLData>
...
<Type>3</Type>
...
</XMLData>

The final output I need is single combined as follows:

<AllMyData>
    <XMLData>
        ...
        <Type>1</Type>
        ...
    </XMLData>
    <XMLData>
        ...
        <Type>2</Type>
        ...
    </XMLData>
    <XMLData>
        ...
        <Type>3</Type>
        ...
    </XMLData>
<AllMyData>

NOTE - all the independent elements that I am combining have the same tag name.

Thanks in advance for looking this up.


Solution

  • I have the following XML generated from various tables in my SQL SERVER database

    Depends on how you have it but if it is in a XML variable you can do like this.

    declare @XML1 xml
    declare @XML2 xml
    declare @XML3 xml
    
    set @XML1 = '<XMLData><Type>1</Type></XMLData>'
    set @XML2 = '<XMLData><Type>2</Type></XMLData>'
    set @XML3 = '<XMLData><Type>3</Type></XMLData>'
    
    select @XML1, @XML2, @XML3 
    for xml path('AllMyData')