3

我想为递归查询设置一个限制。但我不想丢失我限制递归的最后一个条目。

现在查询看起来像这样:

WITH MyCTE (EmployeeID, FirstName, LastName, ManagerID, level, SPECIAL)
AS ( 
    SELECT a.EmployeeID, a.FirstName, a.LastName, a.ManagerID, 0 as Level
    FROM MyEmployees as a
    WHERE ManagerID IS NULL

    UNION ALL
    SELECT b.EmployeeID, b.FirstName, b.LastName, b.ManagerID, level + 1
    FROM MyEmployees as b
    INNER JOIN MyCTE ON b.ManagerID = MyCTE.EmployeeID
    WHERE b.ManagerID IS NOT NULL and b.LastName != 'Welcker' 
)
SELECT *
FROM MyCTE
OPTION (MAXRECURSION 25) 

它受到 Manager Welcker 的限制,结果如下所示:

EmployeeID; FirstName; LastName; ManagerID; level
1           Ken        Sánchez   NULL       0

我想要的是让员工“Welcker”包括在内。问题是我的名单上只有我需要的最后一个人的名字。命令结构下面有一些条目,但我不知道它们,我不想看到它们。

这是我想象查询结果的示例。

EmployeeID FirstName LastName ManagerID level
1          Ken       Sánchez  NULL        0
273        Brian     Welcker  1           1

任何帮助将不胜感激

4

3 回答 3

2
WITH MyCTE (EmployeeID, FirstName, LastName, ManagerID, level, NotMatched)
AS ( 
    SELECT a.EmployeeID, a.FirstName, a.LastName, a.ManagerID, 0 as Level, 0 AS NotMatched
    FROM MyEmployees as a
    WHERE ManagerID IS NULL
    UNION ALL
    SELECT b.EmployeeID, b.FirstName, b.LastName, b.ManagerID, level + 1,
           CASE WHEN (MyCTE.LastName = 'Welcker' AND MyCTE.level = 1) THEN 1 ELSE MyCTE.NotMatched END
    FROM MyEmployees as b
    INNER JOIN MyCTE ON b.ManagerID = MyCTE.EmployeeID
)
SELECT *
FROM MyCTE
WHERE NotMatched != 1
于 2012-11-14T19:35:12.587 回答
0

你能把那一行改成b.LastName = 'Welcker'?

于 2012-11-14T17:34:18.553 回答
0
select distinct
   t.b_eid as empId,
   t.b_name as name, 
   case t.b_mid when 0 then null else t.b_mid end as managerId

   --convert(varchar,t.b_eid) + ', ' + 
   --t.b_name + ', ' + 
   --case t.b_mid when '0' then 'null' else convert(varchar,t.b_mid) end
      --as bvals

from(
   select
      coalesce(a.mid, 0) as a_mid,
      a.eid as a_eid,
      a.name as a_name,
      coalesce(b.mid, 0) as b_mid,
      b.eid as b_eid,
      b.name as b_name
   from 
      (values(null,1,'adam'),(null,2,'barb'),(201,3,'chris')) as a(mid,eid,name) cross join 
      (values(null,1,'adam'),(null,2,'barb'),(201,3,'chris')) as b(mid,eid,name)
) as t
where (t.a_mid = t.b_eid or t.a_mid = 0 or t.b_mid = 0) and t.a_name != 'chris'
于 2012-11-14T21:20:20.417 回答