【问题标题】:How to throw a exception in function如何在函数中抛出异常
【发布时间】:2020-04-06 18:28:44
【问题描述】:

如何处理函数调用中的异常? 它有一个单独的函数,根据使用的参数返回 1 或 0。

如果函数is_valid_eventTypesGeographicAddress 抛出0 我想抛出异常。

我不知道如何在这种语法中做到这一点。

select is_valid_eventTypesGeographicAddress (in_type) from dual ,
             exception WHEN 0 then return  ('Invalid geographic address type');

代码无法编译。

【问题讨论】:

    标签: sql oracle exception plsql


    【解决方案1】:

    您可以使用 PL/SQL 及其RAISE_APPLICATION_ERROR procedure 来引发异常。这是一个例子:

    declare
      myResult number;
    begin
      myResult := is_valid_eventTypesGeographicAddress (in_type);
      if myResult = 0 then
        raise_application_error(-20000, 'Invalid geographic address type');
      end if;
    end;
    

    【讨论】:

      【解决方案2】:

      例外是 PL/SQL 结构。您不能在纯 SQL 中实现异常处理。一种选择是编辑the function so it raises the exception - 或编写一个包装函数来做到这一点。

      create or replace function my_is_valid_eventTypesGeographicAddress (in_type in number) 
      return number 
      is
        rv number;
      begin
      
        rv := is_valid_eventTypesGeographicAddress (in_type);
      
        if rv = 0 then
          raise_application_error (-20000, 'Invalid geographic address type');
        end if;
      
        return rv;
      end;
      

      然后你调用这个版本的函数:

      select my_is_valid_eventTypesGeographicAddress (in_type) from dual;
      

      这有点恶心。通常,我们希望我们的 SQL 能够优雅地成功或失败。因此,您可能需要考虑使用类似这样的原始功能...

      select * from dual
      where is_valid_eventTypesGeographicAddress (in_type) <> 0
      

      ... 然后根据查询是否返回行进行路由控制。

      但我想真正的问题是您为什么要尝试在 SQL 中执行此操作?它似乎应该构成存储过程的一部分。

      【讨论】:

      • 这行不通。检查这个:stackoverflow.com/questions/11191299/…
      • @dmak2709 - 实际上这取决于我们使用的 Oracle 版本。我发布了一个名为 my_is_valid_eventTypesGeographicAddress() on db<>fiddle XE 18c platform 的工作函数。 Oracle 已允许identifiers up to 128 chars since 12c R2。由于 OP 问题中的函数名称是 36 个字符长,我确信他们使用的是最新版本的数据库
      • 还在学习中! :) ...但随后还要更改 select 语句和函数中的 is_valid_eventTypesGeographicAddress 调用。尽管该函数不起作用,因为它只会递归调用自身。我说的对吗?
      猜你喜欢
      • 2017-08-13
      • 2023-01-11
      • 1970-01-01
      • 2022-07-27
      • 1970-01-01
      • 2015-11-06
      • 1970-01-01
      • 2020-05-01
      • 2015-08-26
      相关资源
      最近更新 更多