generate structured (xml) document from hierarchical table data (T-SQL)

前端 未结 2 527
无人共我
无人共我 2020-12-08 23:55

I have a table like this (simplified):

ID   |   Name  |   Parent
---------------------------------
1    |  IND    |   NULL
2    |  INS    |   5
3    |  CON           


        
2条回答
  •  一个人的身影
    2020-12-09 00:33

    You can also do this without creating a separate function, by including the sub-query as an additional column that returns XML. For example, the following will return a hierarchical XML document containing users and their associated list of roles:

    SELECT 
        FirstName, LastName,
        CONVERT(XML, 
          (SELECT r.UserID, r.RoleID
           FROM global.[UserRole] r
           WHERE r.USerID = [user].UserID
           FOR XML RAW ('Role'), ELEMENTS, root('Roles')
          ))
    FROM global.[user]
    FOR XML RAW ('User'), ELEMENTS, root('Users')
    

提交回复
热议问题