Domanda

Se ho una tabella padre e una tabella figlio in cui non ci può essere un genitore a molti bambini, come posso fare per restituire il seguente codice XML da una stored procedure in una stored procedure?

<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>
È stato utile?

Soluzione

Questo è sicuramente molto più difficile con SQL 2000. Di seguito è una query di esempio che può aiutare a iniziare con questo processo. Vi preghiamo di comprendere che non è esattamente nel formato che si sta cercando. Lo scopo della query è quello di aiutarvi a iniziare ... una spintarella nella giusta direzione.

Il trucco è quello di utilizzare FOR XML EXPLICIT e lavorazione con cura i vostri alias di colonna per controllare il posizionamento degli elementi.

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

Altri suggerimenti

È possibile farlo utilizzando alcuni seleziona nidificazione.

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

Ops, non ho visto che era per SQL-Server-2000.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top