Learning While Aging

How to use conditional CASE statement in Oracle WHERE clause to retrieve data

Here is the table structure that I need to query:

UserID

Type

Name

Department

Status

Classification

Enrollment_Status

Where “Type” and “Department” are foreign keys of the other two tables. The query criteria are:

If the user type is “Student” (type ID = 1), then only retrieve enrolled students (Enrollment_Status = ‘EN’);

If the user type is not “Student” (type ID <> 1), then check Classification field and only retrieve data with Classification <> ‘R’

It is a perfect scenario for using CASE statement in WHERE clause, and here is the complete query in Oracle PL/SQL:

SELECT    U.UserID, U.NAME, 

          D.DEPARTMENT,  U.STATUS, 

          U.CLASSIFICATION

FROM      Users U, Departments D, UserType T    

WHERE CASE WHEN (T.ID = '1') AND  (U.ENROLLMENT_STATUS = 'EN') THEN 1

           WHEN (T.ID <> '1') AND (U.CLASSIFICATION <> 'R') THEN 1

           ELSE 0

      END = 1

AND  U."TYPE" = T.ID 

AND (U.DEPARTMENT = D.DEPARTMENT_CODE (+) )

ORDER BY UserID;

For more information about CASE statement in MS SQL, check here: http://msdn.microsoft.com/en-us/library/ms181765.aspx

For more information about CASE statement in Oracle PL/SQL, check here:

http://download.oracle.com/docs/cd/B10501_01/appdev.920/a96624/04_struc.htm#484

[UPDATE]: I just found out that .NET TableAdapter does not recognize the CASE statement above, thought the above query runs well in Oracle SQL Developer. After further investigation, I realize the above query can be changed to this:

SELECT    U.UserID, U.NAME, 

          D.DEPARTMENT,  U.STATUS, 

          U.CLASSIFICATION

FROM      Users U, Departments D, UserType T    

WHERE 

((T.ID = '1' AND  U.ENROLLMENT_STATUS = 'EN') OR (T.ID <> '1' AND U.CLASSIFICATION <> 'R'))

AND  U."TYPE" = T.ID 

AND (U.DEPARTMENT = D.DEPARTMENT_CODE (+) )

ORDER BY UserID;

And TableAdapter will recognize the above query and execute it without any error.

0 0 votes
Article Rating
3 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
A R
A R
7 months ago

I need to modify the WHERE clause criteria based on a value input by the user. I wrote a simple CTE that obtains as input either a Y or N from the user. Then in the WHERE clause, I want to evaluate that input and if Y, have the WHERE clause run as:
WHERE end_date is null
but if the input is N, then run the query with the WHERE clause as:
WHERE end_date is not null
I’ve tried various things but cannot seem to accomplish this. Please provide any suggestions. Thanks.

A R
A R
7 months ago

I entered a comment a few days ago. Any response?