Raymond Evangelista
Raymond Evangelista

Reputation: 9

SQL ORACLE SELECT CASE and NVL

I would like to ask how to use NVL and CASE in one Statement.

SELECT case 
          when column1 like '% =' then replace(column1,' =','=') 
          else column1 
       end 
from table;

SELECT nvl(SUBSTR(column1, INSTR(column1, 'text1') +3, 
           INSTR(column1, 'text2')-(INSTR(column1, ':text1')+4)),'Default') 
from table;

What I want is to use the output of select statement in case as the column1 in nvl statement.

Upvotes: 0

Views: 1451

Answers (2)

Bobby Durrett
Bobby Durrett

Reputation: 1293

Maybe you could use a sub select:

SELECT nvl(SUBSTR(column2, INSTR(column2, 'text1') +3, 
           INSTR(column2, 'text2')-(INSTR(column2, ':text1')+4)),'Default') 
from 
(
SELECT case 
          when column1 like '% =' then replace(column1,' =','=') 
          else column1 
       end column2
from test);

Upvotes: 1

Sentinel
Sentinel

Reputation: 6449

Unless you are worried about strings with equal signs not appearing at the end of the string, I wouldn't bother with the case statement, and if you are concerned about that, I'd recommend the REGEXP_REPLACE function instead. The following function simply removes a single space preceding the terminating equals sign in the string stored in column1:

REGEXP_REPLACE(column1,' =$','=')

Then put the above function anywhere column1 appears in your select statement.

select COALESCE( SUBSTR( REGEXP_REPLACE(column1,' =$','=')
                       , INSTR(REGEXP_REPLACE(column1,' =$','='), 'text1')+3
                       , INSTR(REGEXP_REPLACE(column1,' =$','='), 'text2')
                       -(INSTR(REGEXP_REPLACE(column1,' =$','='), ':text1')+4))
               , 'Default')
 from table;

Upvotes: 0

Related Questions