CTE替换JOIN

时间:2014-08-20 11:19:09

标签: sql sql-server common-table-expression

我可以在这里使用CTE而不是我的代码吗?这是两个表和我的代码。

tbl1

D_ID    department      employee name            manager name
112         d01         john d                   Peter k
113         d01         Emily f                  kevin s 

tbl2 

Emp_id   employee name    D_ID  
100      john d           112 
200      peter k          112
800      Emily f          113
500      kevin s          113  

我的代码如下,我所做的是在t_ll和员工姓名上加入tbl1和tbl2,然后过滤掉员工的emp_id>中的记录。经理的emp_id。

DECLARE @level nvarchar(MAX) =
(
     select X.D_ID ,x.employee_NAME, x.emp_ID as employee_id, 
         y.manager_name ,y.emp_id as manager_id
) + ' '
from (
    select distinct b.d_id , a.emp_id as employee_id 
    from tbl1  a , tbl2 b 
    where a.d_id=b.d_id and a.employee_NAME=b.employee_NAME
) x ,
(
    select distinct b.d_id , a.emp_id as manager_id
    from tbl1  a , tbl2 b 
    where a.d_id=b.d_id and a.employee_NAME=b.manager_NAME
) Y
where x.department=y.department and x.employee_id>=y.manager_id

FOR XML PATH('')
)
IF @level IS NOT NULL
        BEGIN
            RAISERROR(' employee ID>manager_id:  %s',16, 1, @level) 
            with log;
        END;    

希望输出如下,因为Emily f的员工ID是>而不是她的经理的身份证。

 D_ID  employee_NAME  employee_id manager_name  manager_id 
 113   Emily f         800        kevin s       500

1 个答案:

答案 0 :(得分:1)

我认为你只需要一些联接:

select t1.d_id, t1.employee_name, te.emp_id,
       t1.employee_name as manager_name, tm.emp_id as manager_id
from tbl1 t1 join
     tbl2 te
     on t1.employee_name = te.employee_name join
     tbl2 tm
     on t1.manager_name = tm.employee_name
where te.emp_id > tm.emp_id;

很奇怪您使用名称来连接两个表。通常,您将使用员工ID来实现此目的,并使用ID查找名称。