3

I've a query with following structure

select t1.Col1
      ,t1.Col2
      ,(
         select t2.Col1
               ,t2.Col2
           from #t2 t2
          where t1.Col1 = t2.Col1
            for xml path ('Path1'), root('RootPath1'),Type
        )
  from #t1 t1
   for xml path ('Path2')

I want to union it with another query so that the structure would be as following:

    select t1.Col1
          ,t1.Col2
          ,(
             select t2.Col1
                   ,t2.Col2
               from #t2 t2
              where t1.Col1 = t2.Col1
                for xml path ('Path1'), root('RootPath1'),Type
            )
      from #t1 t1
       for xml path ('Path2')
union
    select t1.Col11
          ,t1.Col22
          ,(
             select t22.Col11
                   ,t22.Col22
               from #t22 t22
              where t11.Col11 = t22.Col11
                for xml path ('Path11'), root('RootPath11'),Type
            )
      from #t11 t11
       for xml path ('Path22')

How can I do this? Simple union returns error.

I try to union two queries into one xml and I expect xml to be as follows:

<Path2>
  <RootPath1>
    <Path1>
      <Col1></Col1>
      <Col2></Col2>
    </Path1>
  </RootPath1>
</Path2>
<Path22>
  <RootPath11>
    <Path11>
      <Col11></Col11>
      <Col22></Col22>
    </Path11>
  </RootPath11>
</Path22>
2
  • What error does "simple union" return? Does union all return the same error? Commented May 18, 2015 at 12:02
  • @GordonLinoff, union all returns error either. error is Incorrect syntax near the keyword 'union'. Commented May 18, 2015 at 12:04

1 Answer 1

1

You can try using 2 XML variables and another FOR XML to combine them like so :

declare @path2 XML = (select t1.Col1
          ,t1.Col2
          ,(
             select t2.Col1
                   ,t2.Col2
               from #t2 t2
              where t1.Col1 = t2.Col1
                for xml path ('Path1'), root('RootPath1'),Type
            )
      from #t1 t1
       for xml path ('Path2'))

declare @path22 XML = (select t1.Col11
          ,t1.Col22
          ,(
             select t22.Col11
                   ,t22.Col22
               from #t22 t22
              where t11.Col11 = t22.Col11
                for xml path ('Path11'), root('RootPath11'),Type
            )
      from #t11 t11
       for xml path ('Path22'))

select @path2, @path22
for xml path('')
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, exactly what I want. Can you please help me to add beginning tags to this xml: <?xml version="1.0" encoding="UTF-8"?>
@SherzodMuminov You're welcome. Don't know, but you can always search : link1, link2

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.