top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

How to create recursive query in SQL Server?

+1 vote
465 views
How to create recursive query in SQL Server?
posted Sep 26, 2014 by Rahul Singh

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

2 Answers

0 votes
WITH virtab AS
( 
--anchor select
SELECT col1, col2, col3, col4
FROM tab1 a
WHERE AreaName = 'Canada'
UNION ALL
--recursive select
SELECT col1, col2, col3, col4
FROM tab1 b
INNER JOIN virtab ON a.col1 = b.col4
) 
SELECT * FROM virtab
where col3= 'XXX' ;
answer Sep 29, 2014 by Manish Tiwari
0 votes
 DECLARE @tbl TABLE (
         Id INT
        ,[Name] VARCHAR(20)
        ,ParentId INT
        )

    INSERT INTO @tbl( Id, Name, ParentId )
    VALUES
     (1, 'Europe', NULL)
    ,(2, 'Asia',   NULL)
    ,(3, 'Germany', 1)
    ,(4, 'UK',      1)
    ,(5, 'China',   2)
    ,(6, 'India',   2)
    ,(7, 'Scotland', 4)
    ,(8, 'Edinburgh', 7)
    ,(9, 'Leith', 8)

    ;
WITH  abcd
        AS (
              -- anchor
            SELECT  id, [Name], ParentID,
                    CAST(([Name]) AS VARCHAR(1000)) AS "Path"
            FROM    @tbl
            WHERE   ParentId IS NULL
            UNION ALL
              --recursive member
            SELECT  t.id, t.[Name], t.ParentID,
                    CAST((a.path + '/' + t.Name) AS VARCHAR(1000)) AS "Path"
            FROM    @tbl AS t
                    JOIN abcd AS a
                      ON t.ParentId = a.id
           )
SELECT * FROM abcd
answer Nov 15, 2014 by Manikandan J
...