oracle sql: check individuals in list of values for presence in table
Somebody mailed me 开发者_C百科a list with codes, and I need to check whether each code does exist in an oracle 10 database table.
list looks something like:
code1, code2, code3
Of course for every item in the list i can do
select id from my_table where code = 'code1'.
But this would be time consuming, and not a very elegant. I would like to report back a list like:
code1 present
code2 X
code3 X
code4 present
I'm vaguely aware of oracle's With statement, but I'm not sure how to use it with a list of values instead of a subquery.
The inverse can be achieved like this (see all codes from the database, and check whether they are in the list provided by your colleague):
select code, case when code in ('code1', 'code2', 'code3')
then 'present'
else 'X' end
from my_table;
If that won't work for you, you can try this:
-- you need a special type for your request. Adapt dimensions if necessary
create type codes as varray(100) of varchar(100);
select c.column_value, case when exists (
select 1
from my_table m
where m.code = c.column_value
) then 'present' else 'X' end
from table(codes('code1', 'code2', 'code3')) c;
-- drop that type again
drop type codes;
精彩评论