我有以下查询:
SELECT
101 AS TeacherID
,s.ID
,s.First
,s.Last
FROM dbo.Students s
FOR XML PATH('Student'), ROOT('Students')
生成输出:
<Students>
<Student>
<TeacherID>101</TeacherID>
<ID>14</ID>
<First>Mark</First>
<Last>Smith</Last>
</Student>
<Student>
<TeacherID>101</TeacherID>
<ID>15</ID>
<First>Josephina</First>
<Last>Hewitt</Last>
</Student>
</Students>
我想将每个组分成自己的行(放入单个XMLFormat列):
AdministratorID AdministratorName XMLFormat
------------------------------------------------------------------------------------------------------------------------------------
125 Bertha <Student><TeacherID>101</TeacherID><ID>14</ID><First>Mark</First><Last>Smith</Last></Student>
125 Bertha <Student><TeacherID>101</TeacherID><ID>15</ID><First>Josephina</First><Last>Hewitt</Last></Student>
我尝试使用表格和列别名方法:
SELECT 125 AS AdministratorID,
'Bertha' AS AdministratorName,
t.c AS XMLFormat
FROM
(
SELECT
101 AS TeacherID
,s.ID
,s.First
,s.Last
FROM dbo.Students s
FOR XML PATH('Student'), ROOT('Students')
) t(c)
但是此查询生成单行数据,整个XML位于单个XMLFormat字段中。
我认为我可能需要使用.nodes()方法,但是当我将.nodes('/ Students / Student')添加到t(c)别名时,我得到''语法不正确'。'。< / p>
我想避免在使用.nodes()方法之前将数据放入XML变量,因为文本可能很长。
答案 0 :(得分:2)
select
125 as AdministratorID,
'Bertha' as AdministratorName,
(
select
101 as TeacherID, s.ID, s.First, s.Last
for xml path('Student'), type
) as XMLFormat
from dbo.Students s