使用递归查询的存储过程

时间:2018-05-30 12:21:12

标签: sql sql-server stored-procedures sql-server-2005

我正在编写一个存储过程,它应该返回结果,同样的结果将作为输入传递给存储过程,并且在任何特定时间输入和输出相同后递归应该停止。

下面是存储的过程/函数和运行命令(存储过程的新增内容)。

CREATE FUNCTION dbo.Ancestors (@List VARCHAR(MAX))
RETURNS TABLE
AS
RETURN
WITH CTE AS
(
 SELECT DISTINCT Child AS RESULT FROM example WHERE Parent IN( SELECT Id = 
 Item FROM dbo.SplitInts(@List, ',')) or child IN (SELECT Id = Item FROM 
 dbo.SplitInts(@List, ','))
 UNION ALL
 SELECT DISTINCT Parent AS RESULT FROM example WHERE Parent IN( SELECT Id = 
 Item FROM dbo.SplitInts(@List, ',')) or child IN (SELECT Id = Item FROM 
 dbo.SplitInts(@List, ','))
 )
SELECT RESULT FROM CTE
UNION
SELECT RESULT FROM CTE
GO

CREATE PROCEDURE GetAncestors (@thingID VARCHAR(MAX))
AS
SELECT RESULT FROM dbo.Ancestors(@thingID)
GO

EXEC GetAncestors @thingID = '100'    
  

结果是 - ' 100,101'

EXEC GetAncestors @thingID = '100,101'
  

结果是 - ' 100,101,102'

EXEC GetAncestors @thingID = '100,101,102'
  

结果是 - ' 100,101,102'

我实际想要的是通过传递100或101或102

来一次性给出结果
  

结果应为 - ' 100,101,102'

以下是示例表:

|     Parent          |     Child        |
|---------------------|------------------|
|      100            |      101         |
|---------------------|------------------|
|      101            |      102         |
|---------------------|------------------|

1 个答案:

答案 0 :(得分:1)

看起来你需要一个简单的递归查询,从给定节点开始遍历树。 CTE返回对(Parent, Child)对的列表,因此我将它们组合在一起以获取单个节点的列表(并在此过程中删除重复项)。

请注意,查询是递归的。 CTE(公用表表达式)引用自身。

示例数据

我添加了几行来实际查看正在发生的事情。

DECLARE @T TABLE (Parent int, Child int);

INSERT INTO @T VALUES
(100, 101),
(101, 102),
(102, 103),
(103, 104),
(101, 108),
(108, 109),
(208, 209),
(209, 210);

<强>查询

WITH
CTE
AS
(
    SELECT
        Parent, Child
    FROM @T
    WHERE Parent = 100

    UNION ALL

    SELECT
        T.Parent, T.Child
    FROM
        CTE
        INNER JOIN @T AS T ON T.Parent = CTE.Child
)
SELECT
    Parent AS Result
FROM CTE

UNION

SELECT
    Child AS Result
FROM CTE
;

<强>结果

Result
100
101
102
103
104
108
109

您可以将查询放在存储过程中,如下所示:

CREATE PROCEDURE GetAncestors(@thingID int)
AS
BEGIN
    SET NOCOUNT ON;

    WITH
    CTE
    AS
    (
        SELECT
            Example.Parent, Example.Child
        FROM Example
        WHERE Parent = @thingID

        UNION ALL

        SELECT
            Example.Parent, Example.Child
        FROM
            CTE
            INNER JOIN Example ON Example.Parent = CTE.Child
    )
    SELECT
        Parent AS Result
    FROM CTE

    UNION

    SELECT
        Child AS Result
    FROM CTE
    ;

END
GO