Query to get XML output for hierarchical data using FOR XML PATH in SQL Server

前端 未结 2 1453
你的背包
你的背包 2021-02-14 10:59

I have a table with columns NodeId, NodeName, ParentNodeId and I want to ouput entire table data in the form of Xml like the following using SQL query. I think FOR XML PATH mode

2条回答
  •  终归单人心
    2021-02-14 11:34

    This query will do it - however, it's not very clean in that you have to "manually" define the nesting and it won't just automatically scale to more levels deep....

    SELECT 
        n.ID AS '@Id', 
        n.NAME AS '@Name',
        (SELECT 
            n2.ID AS '@Id', 
            n2.NAME AS '@Name',
            (SELECT 
                n3.ID AS '@Id', 
                n3.NAME AS '@Name'
             FROM 
                dbo.Nodes n3
             WHERE 
                 n3.ParentNode = n2.ID
             FOR XML PATH('Node'), TYPE
            ) 
         FROM 
            dbo.Nodes n2
         WHERE 
             n2.ParentNode = n.ID
         FOR XML PATH('Node'), TYPE
        ) 
    FROM 
        dbo.Nodes n
    WHERE 
        n.ParentNode IS NULL
    FOR XML PATH('Node'), ROOT('Nodes')
    

    Output is:

    
      
        
          
          
        
      
      
        
          
          
        
      
    
    

    I was hoping there would be a way to do this with a recursive CTE (Common Table Expression), but that didn't work out :-(

提交回复
热议问题