SQL Server: How to save treeview nested node collection in table

Sudip Bhatt 2,276 Reputation points
2020-09-21T17:44:11.783+00:00

Please see my xml which has nested node collection. now i want to store this xml with parent-child relation in database table. please guide me how could i write code to save this relation in xml format in db tables?

<?xml version="1.0" encoding="us-ascii" ?> 
<TreeView>
   <node text="Asia">
    <node text="China">
      <node text="Beijing"/>
    </node>
    <node text="Pakistan"/> 
    <node text="India"/> 
    <node text="Srilanka"/> 
   </node>
   <node text="Europe">
      <node text="Germany"/> 
      </node>
   <node text="America"/> 
   <node text="Africa"/> 
</TreeView>

please help me with sql code sample

SQL Server
SQL Server
A family of Microsoft relational database management and analysis systems for e-commerce, line-of-business, and data warehousing solutions.
13,685 questions
Transact-SQL
Transact-SQL
A Microsoft extension to the ANSI SQL language that includes procedural programming, local variables, and various support functions.
4,625 questions
{count} votes

Accepted answer
  1. Viorel 116.6K Reputation points
    2020-09-22T04:39:35.917+00:00

    In case of table that keeps the text, node ID and parent node ID, and does not have a row for root node, check this variation too:

    drop table if exists Tree  
      
    create table Tree   
    (   
        id int NOT NULL PRIMARY KEY,   
        parent_id int REFERENCES Tree(id),   
        [text] nvarchar(max) NOT NULL   
    )  
      
    declare @xml as xml = '<?xml version="1.0" encoding="us-ascii" ?>   
     <TreeView>  
        <node text="Asia">  
         <node text="China">  
           <node text="Beijing"/>  
         </node>  
         <node text="Pakistan"/>   
         <node text="India"/>   
         <node text="Sri Lanka"/>   
        </node>  
        <node text="Europe">  
          <node text="Germany"/>   
        </node>  
        <node text="America"/>   
        <node text="Africa"/>   
     </TreeView>  
    '  
      
      
    ;  
    with Q1 as  
    (  
        select   
            n.query('.') as x,   
            cast(NULL as nvarchar(max)) as txt,  
            cast(0x as varbinary(max)) as p   
        from @xml.nodes('/') n(n)  
        union all  
        select   
            n.query('.'),   
            v.txt,   
            p + cast(cast((ROW_NUMBER() over (order by v.txt)) as int) as varbinary(max))  
        from Q1  
        cross apply x.nodes('*/node') n(n)  
        cross apply (values (n.value('@text', 'nvarchar(max)'))) as v(txt)  
    ),  
    Q2 as  
    (  
        select txt, p, ROW_NUMBER() over(order by len(p), p) as id  
        from Q1  
        where p <> 0x  
    ),  
    Q3 as  
    (  
        select Q2.id, a.id as parent_id, Q2.txt  
        from Q2  
        left join Q2 as a on a.p = substring(Q2.p, 1, len(Q2.p)-4)  
    )  
    insert into Tree  
    select * from Q3  
      
      
    select * from Tree order by 1  
    

    The output:

    id parent_id text
    1 NULL Africa
    2 NULL America
    3 NULL Asia
    4 NULL Europe
    5 3 China
    6 3 India
    7 3 Pakistan
    8 3 Sri Lanka
    9 4 Germany
    10 5 Beijing

    2 people found this answer helpful.

2 additional answers

Sort by: Most helpful
  1. Erland Sommarskog 110.4K Reputation points MVP
    2020-09-21T21:33:35.553+00:00

    I am not sure that I understand the question. Do you want to store the data in the XML in relational format? But you say "save this relation in xml format". Which certainly sounds like you want to store the XML as-is. Which is no different from storing an int or a string. You define a column of the xml data type, and you pass a variable of the same data type.

    Or could you clarify what you need help with?

    1 person found this answer helpful.

  2. Monalv-MSFT 5,896 Reputation points
    2020-09-22T02:03:27.813+00:00

    Hi @Sudip Bhatt ,

    Hope the following links will be helpful:

    1.Adjacency list vs. nested sets: SQL Server

    2.How to represent a data tree in SQL?

    Best Regards,
    Mona


    If the answer is helpful, please click "Accept Answer" and upvote it.
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    1 person found this answer helpful.
    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.