如何在SQL Server 2005中使用存储过程从CTE层次结构数据中获取所有子项及其本身 [英] How To Get All children and itself from Hierarchical data with CTE In SQL Server 2005 using stored procedure

查看:108
本文介绍了如何在SQL Server 2005中使用存储过程从CTE层次结构数据中获取所有子项及其本身的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有许多类似的结构表,例如:

I have many similar structure tables like this:

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的参数吗?

Can you help me writing such as a stored procedure including two parameters with table name and ID ?

例如,执行时

EXEC usp_getChildbyID  tbl_Hierarchy, 1

结果集应为:

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

非常感谢。

推荐答案

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

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


$ b中选择ID,文本,级别$ b

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

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

编辑:

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

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

这篇关于如何在SQL Server 2005中使用存储过程从CTE层次结构数据中获取所有子项及其本身的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆