How To Get All children and itself from Hierarchical data with CTE In SQL Server 2005 using stored procedure

我的未来我决定 提交于 2019-12-04 16:33:22

This recursive CTE should do the trick.

WITH RecursiveCte AS
(
    SELECT 1 as Level, H1.Id, H1.ParentId, H1.Text FROM tbl_Hierarchy H1
    WHERE id = @Id
    UNION ALL
    SELECT RCTE.level + 1 as Level, H2.Id, H2.ParentId, H2.text FROM tbl_Hierarchy H2
    INNER JOIN RecursiveCte RCTE ON H2.ParentId = RCTE.Id
)
SELECT Id, Text, Level FROM RecursiveCte

If you really want it with a dynamic table in a procedure this could be a solution

CREATE PROCEDURE usp_getChildbyID
    @TableName nvarchar(max),
    @Id int
AS
BEGIN

    DECLARE @SQL AS nvarchar(max)
    SET @SQL = 
    'WITH RecursiveCte AS
    (
        SELECT 1 as Level, H1.Id, H1.ParentId, H1.Text FROM ' + @TableName + ' H1
        WHERE id = ' + CAST(@Id as Nvarchar(max)) + '
        UNION ALL
        SELECT RCTE.level + 1 as Level, H2.Id, H2.ParentId, H2.text FROM ' + @TableName + ' H2
        INNER JOIN RecursiveCte RCTE ON H2.ParentId = RCTE.Id
    )
    select Id, Text, Level from RecursiveCte'

    EXEC sp_executesql @SQL;
END

Edit:

Sql fiddle example: http://sqlfiddle.com/#!3/d498b/22

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!