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

前端 未结 2 1447
你的背包
你的背包 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:42

    I solved it using a stored procedure and a recursive function. code shown below. (actually I wanted this to generate a menu xml, so the code is shown for the menu.

        CREATE PROCEDURE [dbo].[usp_GetMenu]
        AS
        BEGIN
            SET NOCOUNT ON;
    
            SELECT  dbo.fnGetMenuItems(MenuId)
            FROM    dbo.Menu
            WHERE   ParentMenuId IS NULL
            FOR XML PATH('MenuItems')
        END
        GO
    
    CREATE FUNCTION [dbo].[fnGetMenuItems]
    (
        @MenuId int
    )
    RETURNS XML
    WITH RETURNS NULL ON NULL INPUT
    AS
    BEGIN
    
        RETURN 
        (
            SELECT  MenuId AS "@Id"
                    , [Name] AS "@Name"
                    , [URL] AS "@URL"
                    , [Key] AS "@Key"
                    , [dbo].[fnGetMenuItems](MenuId)
            FROM    dbo.Menu
            WHERE   ParentMenuId = @MenuId
            FOR XML PATH('MenuItem'),TYPE
        )
    
    END
    GO
    

提交回复
热议问题