user2405778
user2405778

Reputation: 497

Case statement within select case statement

I am trying to create a case statement to work but I seem to be messing up the syntax somehow. Here is what I have so far:

SELECT lp.assign_date, CASE WHEN lp.assign_date > '01-JAN-13' 
THEN
  (select count(*) > 0 THEN 'BAD' ELSE 'GOOD' END
   FROM transaction_table
   WHERE ACCOUNT = :V_ACCT
   AND transaction_date < :V_TRAN_DATE
   AND transaction_code = :V_TRAN_CODE 
   AND :V_TRAN_CODE IN (1,6,25)
   AND attorney_id = :V_ATTY_ID)
ELSE
  (SELECT
   function_legal_chk(:V_ACCT, :V_TRAN_DATE)
   FROM dual)
FROM legal_placement lp;

Essentially its checking to see if the assigned date is after January, if it is then do the next case statement else do the function.

Here is the error that I am receiving:

ORA-00923: FROM keyword not found where expected
00923. 00000 -  "FROM keyword not found where expected"

From what I know and research that I've done on case statements, my syntax seems to be correct but I am not sure if a case within a case is something that can be done.

Any help is much appreciated.

Upvotes: 0

Views: 3755

Answers (2)

Janick Bernet
Janick Bernet

Reputation: 21184

There's definitely a syntax error in

select count(*) > 0 THEN 'BAD' ELSE 'GOOD' END

It should be

select CASE WHEN count(*) > 0 THEN 'BAD' ELSE 'GOOD' END

Also, as pointed out by @GordonLindoff, you don't need the second subquery:

(SELECT
function_legal_chk(:V_ACCT, :V_TRAN_DATE)
FROM dual)

Can just be written as

function_legal_chk(:V_ACCT, :V_TRAN_DATE)

And finally, make sure function_legal_chk returns a Varchar (or Char) like it does in the first first WHEN expression, since they have to be that same type of course.

Upvotes: 1

Gordon Linoff
Gordon Linoff

Reputation: 1269763

Here is correct syntax:

SELECT lp.assign_date,
       (CASE WHEN lp.assign_date > '01-JAN-13' 
             THEN (select (CASE WHEN count(*) > 0 THEN 'BAD' ELSE 'GOOD' END)
                   FROM transaction_table
                   WHERE ACCOUNT = :V_ACCT
                     AND transaction_date < :V_TRAN_DATE
                     AND transaction_code = :V_TRAN_CODE 
                     AND :V_TRAN_CODE IN (1,6,25)
                     AND attorney_id = :V_ATTY_ID
                 )
             ELSE function_legal_chk(:V_ACCT, :V_TRAN_DATE)
        END)
FROM legal_placement lp;

The nested case statement either has to be entirely in the subquery (as shown above) or entirely outside. Your original has it half-and-half. Also, you don't need a subquery to call a function in a select. It is technically ok, but unnecessary.

Upvotes: 1

Related Questions