shahroz shahroz - 7 months ago 8
SQL Question

How can I write a procedure for ...?

My data is :

enter image description here

My procedure code is:

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


How do I return like data:

enter image description here

Answer
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)

Output:

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