2015-04-15 66 views
3

我試圖用SQL Server 2008的FOR XML PATH功能進行實驗。但是我沒有得到我期望的輸出。在根元素上添加weekname的SQL Server XML路徑

我有這樣的一個表:

 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輸出中每一行的weekname?

回答

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