oracle if (select count(column) from table) > 0 then
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10200281/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
if (select count(column) from table) > 0 then
提问by user1339913
I need to check a condition. i.e:
我需要检查一个条件。IE:
if (condition)> 0 then
update table
else do not update
end if
Do I need to store the result into a variable using select into?
我是否需要使用 select into 将结果存储到变量中?
e.g:
例如:
declare valucount integer
begin
select count(column) into valuecount from table
end
if valuecount > o then
update table
else do
not update
回答by Jon Heller
You cannot directly use a SQL statement in a PL/SQL expression:
不能在 PL/SQL 表达式中直接使用 SQL 语句:
SQL> begin
2 if (select count(*) from dual) >= 1 then
3 null;
4 end if;
5 end;
6 /
if (select count(*) from dual) >= 1 then
*
ERROR at line 2:
ORA-06550: line 2, column 6:
PLS-00103: Encountered the symbol "SELECT" when expecting one of the following:
...
...
You must use a variable instead:
您必须改用变量:
SQL> set serveroutput on
SQL>
SQL> declare
2 v_count number;
3 begin
4 select count(*) into v_count from dual;
5
6 if v_count >= 1 then
7 dbms_output.put_line('Pass');
8 end if;
9 end;
10 /
Pass
PL/SQL procedure successfully completed.
Of course, you may be able to do the whole thing in SQL:
当然,您可以使用 SQL 完成整个操作:
update my_table
set x = y
where (select count(*) from other_table) >= 1;
It's difficult to prove that something is not possible. Other than the simple test case above, you can look at the syntax diagramfor the IF
statement; you won't see a SELECT
statement in any of the branches.
很难证明某事是不可能的。除了简单的测试案例上面,你可以看一下语法图的IF
说明; 您不会SELECT
在任何分支中看到语句。
回答by Bohemian
Edit:
编辑:
The oracle tag was not on the question when this answer was offered, and apparently it doesn't work with oracle, but it does work with at least postgres and mysql
提供此答案时,问题上没有 oracle 标签,显然它不适用于 oracle,但它至少适用于 postgres 和 mysql
No, just use the value directly:
不,直接使用值:
begin
if (select count(*) from table) > 0 then
update table
end if;
end;
Note there is no need for an "else".
请注意,不需要“其他”。
Edited
已编辑
You can simply do it all withinthe update statement (ie no if
construct):
您可以简单地在更新语句中完成所有操作(即无if
构造):
update table
set ...
where ...
and exists (select 'x' from table where ...)