2011-01-20 60 views
12

我有這個表結構。 YearPart,MonthPart和日期部分包含他們描述一下... EX:2011,1,19(分別)SQL「For XML Path」 - 嵌套結果

DECLARE @agenda AS TABLE (
    PID INT IDENTITY(1,1) PRIMARY KEY, 
    YearPart int, 
    MonthPart int, 
    DayPart int, 
    lib_title nvarchar(200), 
    [filename] nvarchar(255), 
    meta_value nvarchar(2000) 
) 

使用此示例數據:

INSERT INTO @agenda VALUES (2010, 12, 4, 'Test Record', '', '') 
INSERT INTO @agenda VALUES (2011, 1, 3, 'Another Record', '', '') 
INSERT INTO @agenda VALUES (2011, 1, 3, 'Fred Birthday', '', '') 
INSERT INTO @agenda VALUES (2011, 1, 4, 'Work Day', '', '') 
INSERT INTO @agenda VALUES (2011, 12, 6, '2nd Test Record', '', '') 

我想,就像是一個XML輸出這個:

<root> 
    <Year Year="2010"> 
    <Month Month="12"> 
     <Day Day="4"> 
     <Item RecordName="Test Record" RecordID="1" /> 
     </Day> 
    </Month> 
    </Year> 
    <Year Year="2011"> 
    <Month Month="1"> 
     <Day Day="3"> 
     <Item RecordName="Another Record" RecordID="2" /> 
     <Item RecordName="Geoffrey Birthday" RecordID="3" /> 
     </Day> 
     <Day Day="4"> 
     <Item RecordName="Work Day" RecordID="4" /> 
     </Day> 
    </Month> 
    <Month Month="12"> 
     <Day Day="6"> 
     <Item RecordName="2nd Test Record" RecordID="5" /> 
     </Day> 
    </Month> 
    </Year> 
</root> 

到目前爲止,我還沒有能夠讓嵌套正常工作。我通常最終將分組關閉(例如,我得到多個Year = 2011元素,但應該只有一個)。

如果這不能做,我隨時可以創建基於.NET的網站上的XML ...

回答

16

這是可以做到。

select 
    a1.YearPart as '@Year', 
    (select MonthPart as '@Month', 
     (select DayPart as '@Day', 
     (select 
      lib_title as '@RecordName', 
      PID as '@RecordID' 
      from @agenda as a4 
      where a4.DayPart = a3.DayPart and 
       a4.MonthPart = a2.MonthPart and 
       a4.YearPart = a1.YearPart 
      for xml path('Item'), type   
     ) 
     from @agenda as a3 
     where a3.YearPart = a1.YearPart and 
      a3.MonthPart = a2.MonthPart 
     group by a3.DayPart 
     for xml path('Day'), type  
    ) 
    from @agenda as a2 
    where a1.YearPart = a2.YearPart 
    group by a2.MonthPart 
    for xml path('Month'), type 
) 
from @agenda as a1 
group by YearPart 
for xml path('Year'), root 
+0

非常好!我知道我很接近......我的團隊錯了......感謝Mikael ......正是我所需要的。 – 2011-01-20 19:20:59