2

我有很多类似的结构表是这样的:

CREATE TABLE [dbo].[tbl_Hierarchy](
[ID] [int]  NOT NULL,
[ParentID] [int] NOT NULL,
[Text] [nvarchar](100)  NOT NULL,
--other field irrelevant to my question
)

INSERT INTO dbo.tbl_Hierarchy VALUES(1,0,'parent1')
INSERT INTO dbo.tbl_Hierarchy VALUES(2,0,'parent2')
INSERT INTO tbl_Hierarchy VALUES(3,1,'child1')
INSERT INTO tbl_Hierarchy VALUES(4,3,'grandchild1')
INSERT INTO  tbl_Hierarchy VALUES(5,2,'child2')

你能帮我写一个包含两个参数的存储过程,表名和 ID 吗?

例如,当执行

EXEC usp_getChildbyID  tbl_Hierarchy, 1

结果集应该是:

ID  Text        Level
1   parent1      1
3   child1       2
4   grandchild1  3

提前非常感谢。

4

1 回答 1

6

这个递归 CTE 应该可以解决问题。

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

如果您真的希望在过程中使用动态表,这可能是一个解决方案

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

编辑:

Sql 小提琴示例:http ://sqlfiddle.com/#!3/d498b/22

于 2012-10-12T13:21:52.303 回答