假设客户表格如下。
cust_id | name | address | language
A | AAA | ZZZZ | en
B | BBB | YYYY |
C | CCC | XXXX | pl
D | DDD | WWWW | en
我想获得一个plsql代码,该代码将接受语言字段的用户输入,以及用户输入时;
1. 'en'; cust_id: A,B should be the result
2. 'pl'; cust_id: C should be the result
3. doesnt input a value; cust_id: A,B,C,D should be the result
select cust_id from customer c where c.language like NVL('&lang','%');
选项1& 2与上面的查询工作正常,但3不会产生任何值。我认为这是因为%运算符不使用空值。任何人都可以帮我修改能够为所有3个选项提供结果的查询吗?
答案 0 :(得分:0)
您可以简单地使用解码,如下例所示:
select *
from (select 'en' col1 from dual union all
select 'en' from dual union all
select 'pl' from dual union all
select null from dual) dummy
where decode('&lang', col1, 1, -- If lang is not null and equals col1, return 1, this will only select raws where lang = col1
null, 1, -- if lang is null return 1, this will select every raw
2) = 1 -- Default equals 2 for everything not fitting col1, will only be used if lang is not null
O / P lang = en:
en
en
O / P lang = en:
pl
O / P lang为空:
en
en
pl
"null"
您的选择应该如上所示:
select cust_id
from customer c
where decode('&lang', col1, 1,
null, 1,
2) = 1;
答案 1 :(得分:0)
您可以使用or
执行此操作:
with customer (cust_id, name, address, language) as
( select 'A', 'AAA', 'ZZZZ', 'en' from dual union all
select 'B', 'BBB', 'YYYY', null from dual union all
select 'C', 'CCC', 'XXXX', 'pl' from dual union all
select 'D', 'DDD', 'WWWW', 'en' from dual )
select * from customer c
where (c.language = '&lang' or '&lang' is null);
答案 2 :(得分:0)
您可以使用以下查询:
select cust_id from customer c where c.language = NVL('&lang', c.language);
当&lang
为null
时,查询将返回customer
表中的所有行。