sql server - Sql return results as xml -
given data:
fname lname apartmentnumber ----------------------------------- david shumer 1 john deer 1 mark ratz 2 steven styer 2
i return xml, did this:
select * table1 xml raw('person'), root('peopleinapartment'), elements
and got result
<peopleinapartment> <person> <fname>david</fname> <lname>shumer</lname> <apartmentnumber>1</apartmentnumber> </person> <person> <fname>john</fname> <lname>deer</lname> <apartmentnumber>1</apartmentnumber> </person> <person> <fname>mark</fname> <lname>ratz</lname> <apartmentnumber>2</apartmentnumber> </person> <person> <fname>steven</fname> <lname>styer</lname> <apartmentnumber>2</apartmentnumber> </person> </peopleinapartment>
is possible group people apartment result this?:
<apartments> <peopleinapartment> <person> <fname>david</fname> <lname>shumer</lname> <apartmentnumber>1</apartmentnumber> </person> <person> <fname>john</fname> <lname>deer</lname> <apartmentnumber>1</apartmentnumber> </person> </peopleinapartment> <peopleinapartment> <person> <fname>mark</fname> <lname>ratz</lname> <apartmentnumber>2</apartmentnumber> </person> <person> <fname>steven</fname> <lname>styer</lname> <apartmentnumber>2</apartmentnumber> </person> </peopleinapartment> </apartments>
sql solution. note subquery must depend on outer columns in group by, t1.apartmentnumber
specifically.
select t1.apartmentnumber , (select t2.fname, t2.lname table1 t2 t2.apartmentnumber = t1.apartmentnumber xml path('person'), type ) peopleinapartment table1 t1 group apartmentnumber xml path('apartment'), root('apartments'), elements
returns data apartment - wise
<apartments> <apartment> <apartmentnumber>1</apartmentnumber> <peopleinapartment> <person> <fname>david </fname> <lname>shumer</lname> </person> <person> <fname>john </fname> <lname>deer </lname> </person> </peopleinapartment> </apartment> <apartment> <apartmentnumber>2</apartmentnumber> <peopleinapartment> <person> <fname>mark </fname> <lname>ratz </lname> </person> <person> <fname>steven</fname> <lname>styer </lname> </person> </peopleinapartment> </apartment> </apartments>
Comments
Post a Comment