我正在尝试构建一个查询,以便使用CTE查询从表中搜索所有父行和子行。
我可以搜索父母并返回孩子或搜索孩子并返回父母,但我无法在一个查询中处理这两种可能性。
我只能完成其中一个UNION ALL查询。
我哪里错了?
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
我收到错误:
声明终止。在语句完成之前,最大递归100已经用尽。
答案 0 :(得分:1)
递归调用UNION ALL之后的第二个选择,直到不再向结果集添加任何行。
因此;
检测周期更复杂,但可以完成。
答案 1 :(得分:1)
尝试使用两种不同的CTE:
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;