简体   繁体   中英

Oracle conditional select

Im sure this is an easy one.

How would I do a conditional value select on a column.

Basically if column1 ='Y' then display as "FOO" else if 'n' display "foobar"

select column1 from table1;

With a simple case expression :

select case column1 when 'Y' then 'FOO' else 'foorbar' end
from table1;

That assume a simple if/else. Your question specifies two values, and you can check both:

select case column1 when 'Y' then 'FOO' when 'n' then 'foorbar' end
from table1;

If you have any column1 values other than Y and n you'd get null ; you can still specify a different value with an else even if you're testing for more than one explicit value:

select case column1 when 'Y' then 'FOO' when 'n' then 'foorbar' else 'bar' end
from table1;

An alternative syntax in Oracle is decode, I like this because it's nice and concise, but basically does the same as the case statement suggested above:

select decode(column1,'Y','FOO','foobar') from table1;

The syntax is as follows: decode( expression , search , result [, search , result]... [, default] ).

Further examples are in Oracles docs: http://www.techonthenet.com/oracle/functions/decode.php

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM