【问题标题】:IF NOT EXISTS In Function PLSQL如果函数 PLSQL 中不存在
【发布时间】:2012-11-21 22:55:33
【问题描述】:

我有一个函数,它在打开游标之前有三个 If/Then 语句。 If/Then 语句在打开游标之前检查有效性。

我想再添加一个 If/Then 有效性检查,但是,它比其他的要复杂一些。下面是一个示例,我已经块评论了我想添加的内容:

begin
    if not procedure.validation_function (<variable>, <condition>=TRUE) then
        return variable2;
    end if;

   /* if not exists
    (
       SELECT 'x' FROM table1
       WHERE table1_id = variable1_id
       AND trunc(sysdate) < trunc(table1_date + 60)
    ) then
        return variable2;
    end if; */

    open cursor(<argument>);
    fetch cursor into <variable>;
    close cursor;
    return <variable>;


end;

我的问题是我来自 T-SQL 世界,我发现在 PL/SQL 中 if not exists 命令不起作用。有没有一种方法可以在函数中使用 SELECT 的 If NO_DATA_FOUND 语句?

有没有办法在其中嵌套另一个函数,所以我可以:

begin
     SELECT ....
     FROM ....
     WHERE ....
        if NO_DATA_FOUND then
           return variable2;
        end if;
end;

【问题讨论】:

  • “如果不存在”作为 T-SQL 工作,它不太清楚你在问什么,我建议你简化你的问题,我看到了函数、ifs 和游标,我得到了搞砸了你在问什么

标签: oracle plsql


【解决方案1】:

Exists条件只能在SQL语句中使用,不能直接在PL/SQL中使用。有几种选择:

  • select 语句中使用case 表达式和exists 条件:

    SQL> declare
      2    l_exists number(1);
      3  begin
      4    select case
      5             when exists(select 1
      6                           from employees
      7                          where department_id = 1)
      8             then 1
      9             else 0
     10           end into l_exists
     11      from dual;
     12  
     13     if (l_exists = 1)
     14     then
     15       dbms_output.put_line('exists');
     16     else
     17       dbms_output.put_line(q'[doesn't exist]');
     18     end if;
     19  end;
     20  /
    
     doesn't exist
    
     PL/SQL procedure successfully completed
    
  • 或者(需要rownum保证多条记录符合条件时只返回一条记录):

    SQL> declare
      2    l_exists number;
      3  begin
      4  
      5    select 1
      6      into l_exists
      7      from employees
      8     where department_id = 100
      9       and rownum = 1;
     10  
     11     dbms_output.put_line('exists');
     12  
     13  exception
     14    when no_data_found
     15    then dbms_output.put_line(q'[doesn't exist]');
     16  end;
     17  /
    
     exists
    
     PL/SQL procedure successfully completed
    

【讨论】:

  • 如果 EMPLOYEES 是一个相当大的表,那么测试是否存在而不是计算所有匹配的行可能会带来真正的好处。但无论如何,EXISTS 变体更清楚地表达了我们的意图:我们不关心 EMPLOYEES 中有 多少 行匹配,只要至少有一个,那么为什么还要费心计算呢?
  • @APC 当然,APC,如果我们只测试是否存在至少一条记录,那么计算每个匹配行是不明智的。我已经修改了答案中的第二种方法以使其更有效。
  • 案例陈述对我来说非常有效。很抱歉迟到接受!谢谢!
猜你喜欢
  • 1970-01-01
  • 2012-02-08
  • 1970-01-01
  • 2020-08-06
  • 1970-01-01
  • 2022-01-20
  • 2021-08-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多