Question

I have the following query:

Select emp_id, emp_name, department, salary
from tbl_employee emp
where (
CASE 
      when emp.department = 'C'
      then (select count(*) from (SELECT 'Y' iscommissioner
                                  FROM tbl_emp_department ted
                                  where ted.department = emp.department )) 

      when emp.department = 'C'
      then (select count(*) from (SELECT 'Y' iscommissioner
                                  FROM tbl_emp_department ted
                                  where ted.department = emp.department
                                  and ted.id = 7))
END)  > 0

I am getting the following error:

emp.department invalid identifier

What am I doing wrong? Why can't I access that column with a table alias in the where clause in a case statement?

Any idea?

Was it helpful?

Solution

This has nothing to do with the case statement. The issue is the scoping rules for correlated subqueries. They only nest one level deep. Here is another question with this problem.

For your example, you don't need nested subqueries. You can just do:

where (CASE when emp.department = 'C'
            then (select count(*) 
                  from tbl_emp_department ted
                  where ted.department = emp.department
                 )
            when emp.department = 'C'
            then (select count(*)
                  from tbl_emp_department ted
                  where ted.department = emp.department and ted.id = 7
                 )
       END)  > 0

However, because your query doesn't really make sense (the same conditions for the two when clauses, I suspect that your actual query may be more complicated. You may have to find another approach to do what you want, using explicit joins and aggregations or using analytic functions.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top