sql-servert-sqlcommon-table-expression

Multiple recursive union all selects in a CTE SQL query


I am trying to build a query for searching all parent and children rows from a table using a CTE query.

I can either search for parents and return children or search for children and return parents but I can not handle both possibilities in the one query.

I can only complete one of the UNION ALL queries.

Where am I going wrong?

declare @search nvarchar(50)

--set @search = '%Nucleus sub project%';
set @search = '%Nucleus test';

WITH Parent AS
(
    SELECT * 
    FROM tblProjects 
    WHERE ProjNo LIKE @search 
       OR ProjDes LIKE @search

    UNION ALL

    SELECT tblProjects.* 
    FROM tblProjects  
    JOIN Parent ON tblProjects.proID = Parent.ParentProjID

    UNION ALL

    SELECT tblProjects.* 
    FROM tblProjects  
    JOIN Parent ON tblProjects.ParentProjID = Parent.proID 
)
SELECT distinct * 
FROM Parent 
ORDER BY ParentProjID

I get an error :

The statement terminated. The maximum recursion 100 has been exhausted before statement completion.


Solution

  • Try using two different CTEs:

    WITH x AS (
        SELECT p.*
        FROM tblProjects p
        WHERE  ProjNo LIKE @search OR ProjDes LIKE @search
       ),
       parents as (
        SELECT * 
        FROM x 
        UNION ALL
        SELECT p.* 
        FROM parents JOIN
             tblProjects p
             ON p.parentid= parents.proID
       ),
       children as (
        SELECT * 
        FROM x 
        UNION ALL
        SELECT p.* 
        FROM children JOIN
             tblProjects p
             ON children.parentid = p.proID
       )
    SELECT distinct * 
    FROM parents
    UNION
    SELECT distinct *
    FROM children;