简体   繁体   中英

Generating nested XML in SQL Server

I am trying to use the FOR XML syntax to take a one table database and generate nested XML using an Azure SQL database.

My table looks like this

TASK Table

NAME    | ID | PARENT
School  |  0 | NULL
Math    |  1 |    0
CSC     |  2 |    0
Eng     |  3 |    0
HW      |  4 |    1
Quiz    |  5 |    1
HW      |  6 |    2
Quiz    |  7 |    2
HW      |  8 |    3
Quiz    |  9 |    3
Hw1     | 10 |    4
Hw2     | 11 |    4

This is what I want the XML to come out like

<Task name=School>  
   <Task name=Math>  
      <Task name=HW>  
         <Task name=Hw1>  
         <Task name=Hw2>  
      <Task name=Quiz>  
   <Task name=CSC>  
      <Task name=HW>  
      <Task name=Quiz>  
   <Task name=Eng>  
      <Task name=HW>  
      <Task name=Quiz>  
<\Task>  

-


SOLUTION FROM @Mikael Eriksson

Go to www.SQLFiddle.com, select SQL Server 2012 in the top left corner.

Enter the following into the Schema panel on the left then 'Build Schema'

create table dbo.Task
(
  Name varchar(10),
  ID int,
  Parent int
);

insert into Task values
('School'  ,  0 , null),
('Math'    ,  1 ,    0),
('CSC'     ,  2 ,    0),
('Eng'     ,  3 ,    0),
('HW'      ,  4 ,    1),
('Quiz'    ,  5 ,    1),
('HW'      ,  6 ,    2),
('Quiz'    ,  7 ,    2),
('HW'      ,  8 ,    3),
('Quiz'    ,  9 ,    3),
('Hw1'     , 10 ,    4),
('Hw2'     , 11 ,    4);

go

create function dbo.GetTaskXML(@ParentID int) returns xml
as
begin
  return (
         select Name as [@name],
                (select dbo.GetTaskXML(ID))
         from dbo.Task
         where Parent = @ParentID or 
               (Parent is null and @ParentID is null)
         for xml path('Task'), type
         )
end

Remember to click on 'Build Schema', Once the schema is built, you can enter your query in the window on the right.

select dbo.GetTaskXML(null)  

Now run query and the bottom window will return the XML results, thanks again Mikael

If your hierarchy is no deeper than 32 levels you can use a recursive scalar valued function that builds the XML.

create function dbo.GetTaskXML(@ParentID int) returns xml
as
begin
  return (
         select Name as [@name],
                (select dbo.GetTaskXML(ID))
         from dbo.Task
         where Parent = @ParentID or 
               (Parent is null and @ParentID is null)
         for xml path('Task'), type
         )
end

SQL Fiddle

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM