具有异常处理的PL / SQL函数

时间:2017-08-31 12:28:49

标签: oracle plsql

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

创建一个名为' find_transaction_type'的函数。这将接受transaction_type_id作为输入。根据此输入,该函数必须返回类型为varchar的事务类型名称。

功能名称:find_transaction_type,

输入参数:int

中的transaction_type_id

设计规则:

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

2)如果事务类型id作为输入传递,与事务表中的id不匹配,则抛出' NO_DATA_FOUND'异常并将其显示为'没有这样的类型'

注意:使用变量打印例外而不是' dbms_output.put_line' 即:umpire_name:='没有这样的裁判员&#39 ;;

我的解决方案是:

    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;
/

我的代码出了什么问题?

2 个答案:

答案 0 :(得分:1)

您不需要第一个选择,也不需要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;

答案 1 :(得分:0)

  1. 使用varchar2而不是varchar。
  2. 在第一个选择语句中添加where子句。
  3. 如果你做2则不需要if then else。