2

我在SQL XML中有以下代码。我需要将父元素插入到 SQL XML 中的父元素中。

我有下表。

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

这是我的 SQL XML 语句

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

结果如下

<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>

我希望以下结果是类和标记标记包含在另一个标记中:

    <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>

知道如何去做吗?

谢谢!

4

1 回答 1

2

您可以使用列别名。

select Firstname,
       Lastname,
       class as "Details/class",
       mark as "Details/mark"
from Student
for xml path('Students'), type
于 2012-06-21T07:38:00.503 回答