【问题标题】:PL/SQL Function with Exception Handling带有异常处理的 PL/SQL 函数
【发布时间】:2017-08-31 12:28:49
【问题描述】:

我是 PL/SQL 的初学者。我需要编写一个包含以下详细信息的函数:

创建一个名为“find_transaction_type”的函数,它将接受 transaction_type_id 作为输入。基于此输入,函数必须返回 varchar 类型的事务类型名称。

函数名:find_transaction_type,

输入参数:transaction_type_id in int

设计规则:

1)如果交易类型id(即transaction_type_id)作为输入传递,与交易表中的id匹配,则返回给定transaction_type_id的类型。

2)如果作为输入传递的事务类型id与事务表中的id不匹配,则抛出'no_data_found'异常并显示为'No such Type'的文本

注意:使用变量而不是 'dbms_output.put_line' 来打印异常 即: umpire_name := '没有这样的裁判';

我的解决方案是:

    create or replace function find_transaction_type(transaction_type_id in integer) return varchar is
           transaction_type_name varchar(255);
           type_id               integer;
           error_msg             varchar(255);
        begin
           error_msg := 'No such Type';
           select id
             into type_id
             from transaction_type;
           if type_id = transaction_type_id
           then
              select type
                into transaction_type_name
                from transaction_type
               where id = transaction_type_id;
              return(transaction_type_name);
           else
              raise no_data_found;
           end if;
        exception
           when no_data_found then
              raise_application_error(-10403, error_msg);
        end;
/

我的代码有什么问题?

【问题讨论】:

  • 除了没有任何缩进使其可读之外? :-) 好吧,您的第一个 select 没有 where 子句,因此将返回来自 transaction_type 的所有行,而不仅仅是您想要的行。

标签: oracle plsql


【解决方案1】:

您不需要第一个 select 也不需要 if 语句。只需让查询引发 no_data_found 异常。按表的各自类型引用类型。

create or replace function find_transaction_type (
    transaction_type_id in transaction_type.transaction_type_id%type
    )
    return transaction_type.type%type is
       transaction_type_name transaction_type.type%type;
    begin
       select type -- not a good column name
         into transaction_type_name -- this should be the column name also
         from transaction_type
        where id = transaction_type_id;
        return transaction_type_name;
    exception
       when no_data_found then
          if transaction_type_id is null then
             raise_application_error(-10403, "type argument is null");
          else
             raise_application_error(-10403, "type '" || transaction_type_id || "' not found");
          end if;
    end;

【讨论】:

    【解决方案2】:
    1. 使用 varchar2 代替 varchar。
    2. 在第一个 select 语句中添加 where 子句。
    3. 如果执行 2,则不需要 if then else。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-12-27
      • 2016-01-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多