我正在尝试使用SQL Server 2008的FOR XML PATH
功能。但我没有得到我预期的输出。
我有一张这样的表:
EventId EventDesc WeekName
--------------------------------
101 A sunday
102 B Monday
103 C wednesaday
如何像这样输出XML:
<Events>
<sunday>
<E>
<NE>
<EventId>101</EventID>
<Name>A</Name>
</NE>
</E>
</sunday>
<Monday>
<E>
<NE>
<EventId>102</EventID>
<Name>B</Name>
</NE>
</E>
</Monday>
<Tuesday>
<E>
<NE>
<EventId>103</EventID>
<Name>C</Name>
</NE>
</E>
</Tuesday>
</Events>
我使用的查询:
select
(select
[EventID] as ID,
[EventDesc] as D
from
TempEvent
where
WeekName = 'sunday'
FOR XML PATH('NE'), Root('E'), type)
FOR XML PATH ('sunday')
我的问题是,如何获取XML输出中每行的工作名?
答案 0 :(得分:2)
它不是最好的解决方案(绝对不优雅),因为它使用字符串连接来构建XML
,但它可以完成工作。
;WITH CTE as
(
SELECT 101 as EventId, 'A' as EventDesc, 'sunday' as WeekName
UNION ALL SELECT 102 as EventId, 'B' as EventDesc, 'Monday'
UNION ALL SELECT 103 as EventId, 'C' as EventDesc, 'wednesaday'
)
SELECT '<Events>' +(
SELECT DISTINCT '<' + WeekName +'>' + (SELECT EventId,EventDesc FROM CTE C2 WHERE C2.WeekName = C1.WeekName FOR XML PATH('NE'),ROOT('E')) + '</' + WeekName +'>'
FROM CTE C1
FOR XML PATH('Events'),TYPE).value('.','NVARCHAR(MAX)') + '</Events>'