基于 select 语句的案例?
Case based on select statement?
而不是做:
select count(*) into l_count from mergetest where a = 1;
case l_count
when 0 then
insert into mergetest (a,b) values (1,1);
when 1 then
update mergetest set b = b + 1 where a = 1;
else
NULL;
end case;
我想摆脱局部变量 l_count
而改为:
case select count(*) from mergetest where a = 1;
...
这可能吗?
似乎无法使用 PL/SQL
来自文档
The value of the CASE operand and WHEN operands in a simple CASE
statement can be any PL/SQL type other than BLOB, BFILE, an object
type, a PL/SQL record, an index-by table, a varray, or a nested table.
http://docs.oracle.com/cd/B19306_01/appdev.102/b14261/case_statement.htm
但是,您可以使用 scalar subquery
select case when dummy = 'X' then (select count(*) from all_users)
else (select count(*) from dual)
end cnt from dual
这可能会解决您的问题。
不,这不可能。它与 PL/SQL 的 CASE 控制结构 无关,而是与 PL/SQL 一般相关。您也不能在 IF 语句中使用它。
因此这段代码也无法编译:
IF (SELECT COUNT(*) FROM MY_TABLE) > 0 THEN ...
请注意,如果 CASE 语句是 SELECT(或类似 SQL) 语句:
SEELCT
p.name,
CASE WHEN P.TYPE_ID = 1 THEN
(SELECT COUNT(*) FROM child c WHERE c.parent_id = p.id)
ELSE 0
END cnt
FROM parent p;
当然,在表达式中不能使用 INSERT 或 UPDATE 等语句。
可以使用 merge
而不是 case
:
来摆脱局部变量
merge into mergetest
using (select 1 a from dual) ins
on (mergetest.a = ins.a)
when matched then
update set mergetest.b = mergetest.b + 1
where (select count(1) from mergetest where mergetest.a = ins.a) = 1
when not matched then insert (mergetest.a, mergetest.b)
values (ins.a, 1)
行:
where (select count(1) from mergetest where mergetest.a = ins.a) = 1
如果 a
已在 table 中存在不止一次,则阻止更新。
而不是做:
select count(*) into l_count from mergetest where a = 1;
case l_count
when 0 then
insert into mergetest (a,b) values (1,1);
when 1 then
update mergetest set b = b + 1 where a = 1;
else
NULL;
end case;
我想摆脱局部变量 l_count
而改为:
case select count(*) from mergetest where a = 1;
...
这可能吗?
似乎无法使用 PL/SQL
来自文档
The value of the CASE operand and WHEN operands in a simple CASE statement can be any PL/SQL type other than BLOB, BFILE, an object type, a PL/SQL record, an index-by table, a varray, or a nested table.
http://docs.oracle.com/cd/B19306_01/appdev.102/b14261/case_statement.htm
但是,您可以使用 scalar subquery
select case when dummy = 'X' then (select count(*) from all_users)
else (select count(*) from dual)
end cnt from dual
这可能会解决您的问题。
不,这不可能。它与 PL/SQL 的 CASE 控制结构 无关,而是与 PL/SQL 一般相关。您也不能在 IF 语句中使用它。
因此这段代码也无法编译:
IF (SELECT COUNT(*) FROM MY_TABLE) > 0 THEN ...
请注意,如果 CASE 语句是 SELECT(或类似 SQL) 语句:
SEELCT
p.name,
CASE WHEN P.TYPE_ID = 1 THEN
(SELECT COUNT(*) FROM child c WHERE c.parent_id = p.id)
ELSE 0
END cnt
FROM parent p;
当然,在表达式中不能使用 INSERT 或 UPDATE 等语句。
可以使用 merge
而不是 case
:
merge into mergetest
using (select 1 a from dual) ins
on (mergetest.a = ins.a)
when matched then
update set mergetest.b = mergetest.b + 1
where (select count(1) from mergetest where mergetest.a = ins.a) = 1
when not matched then insert (mergetest.a, mergetest.b)
values (ins.a, 1)
行:
where (select count(1) from mergetest where mergetest.a = ins.a) = 1
如果 a
已在 table 中存在不止一次,则阻止更新。