Question

Si j'ai une table parent et une table enfant où il peut y avoir un parent à beaucoup d'enfants, comment puis-je aller à retourner le code XML suivant à partir d'une procédure stockée dans une procédure stockée?

<Parents>
    <Parent>
       <ID>Integer</ID>
       <Children>
           <Child>
               <ID>Integer</ID>
               <Text>String</Text>
           </Child>
           <Child>
               <ID>Integer</ID>
               <Text>String</Text>
           </Child>
        </Children>
    </Parent>
    <Parent>
       <ID>Integer</ID>
       <Children>
           <Child>
               <ID>Integer</ID>
               <Text>String</Text>
           </Child>
           <Child>
               <ID>Integer</ID>
               <Text>String</Text>
           </Child>
        </Children>
    </Parent>
</Parents>
Était-ce utile?

La solution

Ceci est certainement beaucoup plus difficile avec SQL 2000. Voici une exemple de requête qui peut vous aider à démarrer avec ce processus. S'il vous plaît comprendre que ce n'est pas exactement dans le format que vous recherchez. Le but de la requête est de vous aider à démarrer ... un petit coup de pouce dans la bonne direction.

L'astuce consiste à utiliser ici FOR XML EXPLICIT et soigneusement vos alias artisanat de colonne pour contrôler le positionnement des éléments.

Declare @Parent Table(Id Int, Data VarChar(20))
Insert Into @Parent Values(1, 'Fruit')
Insert Into @Parent Values(2, 'Vegetable')

Declare @Child Table(Id Int, ParentId Int, Name VarChar(20))
Insert Into @Child Values(1, 1, 'Apple')
Insert Into @Child Values(2, 1, 'Banana')
Insert Into @Child Values(3, 2, 'Carrot')
Insert Into @Child Values(4, 2, 'Pea')

Select 1 As Tag,
       NULL As Parent,
       Id As [Parent!1!Id!Element],
       Data As [Parent!1!Data!Element],
       NULL As [Child!2!Id!Element],
       NULL As [Child!2!Name!Element]
From   @Parent P

Union

Select  2 As Tag,
        1 As Parent,
        P.Id,
        NULL,
        C.Id,
        Name
From    @Child C
        Inner Join @Parent P
          On C.ParentId = P.Id
Order By [Parent!1!Id!Element]
For XML Explicit

Autres conseils

Vous pouvez le faire en utilisant des nids sélectionne.

select 'a' as "ID",
 (
 select child as "ID"
 from ( select 'integer' as child
   union all
   select 'string' ) a
   for xml path('Child'), type, root('Childrens') 
   ) as "*"
for xml path('Parent'), type, root('Parents')

Oups, je ne l'ai pas vu qu'il était pour Sql-Server-2000.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top