SQL “Pour XML Path” imbriquée résultats

J'ai cette structure de table. YearPart, MonthPart et DatePart contenir ce qu'ils décrivent... EX: 2011, 1, 19 (respectivement)

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

À l'aide de cet exemple de données:

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

Ce que je veux, est une sortie XML comme ceci:

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

Jusqu'à présent, je n'ai pas été en mesure d'obtenir l'imbrication de travail de droit. J'ai l'habitude jusqu'à la fin avec le groupement off (par exemple, je reçois plusieurs Année=2011 éléments, quand il ne devrait être qu'un).

Si cela ne peut pas être fait, je peux toujours créer le XML sur le .NET site...

OriginalL'auteur Eric Burdo | 2011-01-20