ngweixiong
ngweixiong

Reputation: 115

Retrieve nested parent child xml based on parent xml in sql xml

i have the following codes in SQL XML. I need to insert a parent element into a parent element in SQL XML.

i have the following table.

Firstname   Lastname    class   mark
John        Lim          V      60
Wills       smith        V      80
Mark        Bay          V      75
Carl        mark         V      65

and this is my SQL XML statements

 Select 
  Firstname,
  Lastname,
  class,
  mark
  from Student for xml path('Students'), type

The result as below

<Students>
  <Firstname>John</Firstname>
  <Lastname>Lim</Lastname>
  <class>V</class>
  <mark>60</mark>
</Students>
<Students>
  <Firstname>Wills</Firstname>
  <Lastname>smith</Lastname>
  <class>V</class>
  <mark>80</mark>
</Students>
<Students>
  <Firstname>Mark</Firstname>
  <Lastname>Bay</Lastname>
  <class>V</class>
  <mark>75</mark>
</Students>
<Students>
  <Firstname>Carl</Firstname>
  <Lastname>mark</Lastname>
  <class>V</class>
  <mark>65</mark>
</Students>

I want the below result were class and mark tag are enclosed in another tag:

    <Students>
  <Firstname>John</Firstname>
  <Lastname>Lim</Lastname>
  <Details>
    <class>V</class>
    <mark>60</mark>
  </Details>  
</Students>
<Students>
  <Firstname>Wills</Firstname>
  <Lastname>smith</Lastname>
  <Details>
    <class>V</class>
    <mark>80</mark>
  </Details>
</Students>
<Students>
  <Firstname>Mark</Firstname>
  <Lastname>Bay</Lastname>
  <Details>
    <class>V</class>
    <mark>75</mark>
  </Details>
</Students>
<Students>
  <Firstname>Carl</Firstname>
  <Lastname>mark</Lastname>
  <Details>
    <class>V</class>
    <mark>65</mark>
  </Details>
</Students>

Any idea how to go about doing this?

Thanks!

Upvotes: 2

Views: 216

Answers (1)

Mikael Eriksson
Mikael Eriksson

Reputation: 139010

You can use a column alias.

select Firstname,
       Lastname,
       class as "Details/class",
       mark as "Details/mark"
from Student
for xml path('Students'), type

Upvotes: 2

Related Questions