我怎样才能为...编写程序?

时间:2016-04-16 10:39:36

标签: sql sql-server

我的数据是:

enter image description here

我的程序代码是:

CREATE PROCEDURE SearchParent
    @ID bigint = 7
AS
BEGIN
    -- how write code to get data like picture down
END
GO

如何返回类似数据:

enter image description here

1 个答案:

答案 0 :(得分:2)

DECLARE @ID bigint = 7

DECLARE @table TABLE 
(
    id bigint,
    name nvarchar(2),
    parentid bigint
)

INSERT INTO @table 
VALUES (1, 'a', 0), (2, 'b1', 1), (3, 'b2', 1),
       (4, 'c1', 2), (5, 'c2', 2), (6, 'd1', 3),
       (7, 'd2', 3)

--This part goes into the procedure
;WITH cte AS  
(
    SELECT 
        id, name, parentid
    FROM 
        @table --change table name to yours
    WHERE 
        id = @ID

    UNION ALL

    SELECT 
        t.*
    FROM 
        cte c 
    INNER JOIN 
        @table t ON c.parentid = t.id
)
SELECT *
FROM cte
ORDER BY id ASC
OPTION (MAXRECURSION 100)

输出:

id   name parentid
---- ---- ---------
1    a    0
3    b2   1
7    d2   3