forki
forki

Reputation: 33

SQL Server : CTE going a level back in the where clause

I would like to set a limit to a recursive query. But I don't want to lose the last entry on which i limited the recursion.

Right now the query looks like this:

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) 

And it gets limited by the Manager Welcker, the result looks like this:

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

What I want is to have the employee 'Welcker' included. The problem is I only have the name of the last person I need to have on my list. There are some entries below in the command structure but I don't know them and I don't want to see them.

Here's a example of how I imagine the result of my query to look.

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

Any help would be very much appreciated

Upvotes: 3

Views: 943

Answers (3)

Oleksandr Fedorenko
Oleksandr Fedorenko

Reputation: 16904

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

Upvotes: 2

C H Vach
C H Vach

Reputation: 100

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'

Upvotes: 0

C H Vach
C H Vach

Reputation: 100

Can you just change that one line to b.LastName = 'Welcker'?

Upvotes: 0

Related Questions