【问题标题】:if (select count(column) from table) > 0 thenif (select count(column) from table) > 0 then
【发布时间】:2012-04-29 07:50:41
【问题描述】:

我需要检查一个条件。即:

if (condition)> 0 then
  update table
else do not update
end if

是否需要使用 select into 将结果存储到变量中?

例如:

declare valucount integer
begin
  select count(column) into valuecount from table
end
if valuecount > o then
  update table
else do 
  not update

【问题讨论】:

    标签: oracle plsql


    【解决方案1】:

    不是很优雅,但你不需要声明任何变量:

    for k in (select max(1) from table where 1 = 1) loop
        update x where column = value;
    end loop;
    

    【讨论】:

      【解决方案2】:

      您不能在 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:
      ...
      ...
      

      您必须改用变量:

      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.
      

      当然,你也许可以在 SQL 中完成所有事情:

      update my_table
      set x = y
      where (select count(*) from other_table) >= 1;
      

      很难证明某事是不可能的。除了上面的简单测试用例,您可以查看syntax diagram 中的IF 语句;您不会在任何分支中看到 SELECT 语句。

      【讨论】:

      • 如果“where”条件失败,如何为 x 设置不同的值?
      • 但是,当整个语句以 [end if;] 终止时,您可以将 select 作为 if 或 else 分支中的一行代码运行。当 if 语句没有正确终止时,开发者界面只是声明将跳过 select 语句,这是一个非常模糊的错误。
      【解决方案3】:

      编辑:

      提供此答案时,oracle 标记不在问题上,显然它不适用于 oracle,但它至少适用于 postgres 和 mysql

      不,直接使用值:

      begin
        if (select count(*) from table) > 0 then
           update table
        end if;
      end;
      

      请注意,不需要“else”。

      已编辑

      您可以在更新语句简单地完成所有操作(即没有if 构造):

      update table
      set ...
      where ...
      and exists (select 'x' from table where ...)
      

      【讨论】:

      • 在 PL/SQL 的情况下你需要一个 into 子句
      • @Sathya 当我回答问题时,“oracle”标签不在问题上 - 这种语法适用于 postgres 和 mysql
      • 天哪,我喜欢 PostgreSQL——所有语句都是函数式编程意义上的表达式——任何返回标量、行/向量或表/矩阵类型值的语句或 proc/func 都可以在任何地方使用一个值是预期的,没有任意的语法限制。
      猜你喜欢
      • 2017-07-04
      • 2014-12-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-01-20
      • 1970-01-01
      • 2014-03-22
      • 2014-12-02
      相关资源
      最近更新 更多