【问题标题】:Nullable return type in oracle functionoracle函数中的可空返回类型
【发布时间】:2015-04-22 09:03:08
【问题描述】:

可以从 oracle 函数返回 null 吗?

我有以下oracle函数:

create or replace function vta.GetAmount(p_month NUMBER)
  return number is
  v_amount number(9);
begin
  select amount
    into v_amount
    from salary
   where salary.month = p_month;
  return v_amount;
end GetAmount;

当 select 语句返回零行时,它会引发以下异常: ora-01403: no data found.

在这种情况下,我希望函数返回 null。

【问题讨论】:

  • 您的 select 语句返回超过 1 行代码失败,而不是因为它返回 0 行。如果它会返回 0 行,则返回 null。
  • 不,如果它返回了 0 行,那么你会得到 no_data_found 异常。
  • 尝试运行这个,从salary.month = 中选择金额:并查看结果;
  • @Rene 现在帖子没问题,否则前面的错误指向我在最初评论中所说的内容
  • 抱歉,在 PL/SQL Developer 中重新测试后,抛出了ORA-01403: no data found 异常。我已经更正了我的问题。

标签: oracle function plsqldeveloper


【解决方案1】:
create or replace function vta.GetAmount(p_month NUMBER)
  return number is
  v_amount number(9);
begin
  select amount
    into v_amount
    from salary
   where salary.month = p_month;
  return v_amount;
  exception   -- code to handle no data
  when no_data_found then
  return null;
  end GetAmount;

【讨论】:

    【解决方案2】:

    当您在 PL/SQL 中执行非批量隐式游标时(这是您对 SELECT ... INTO ... 所做的),您必须记住它需要至少 1 行且最多 1 行。

    如果您获得的行数少于或多于 1 行,您将得到一个异常 - NO_DATA_FOUND 或 TOO_MANY_ROWS,这两者都是不言自明的。

    如果您希望代码在发生任一异常时执行某些操作,那么您将需要处理这些异常。

    例如:

    create or replace function vta.GetAmount(p_month NUMBER)
      return number is
      v_amount number(9);
    begin
      select amount
        into v_amount
        from salary
       where salary.month = p_month;
      return v_amount;
    exception
      when no_data_found then
        return null;
      when too_many_rows then
        return null;
    end GetAmount;
    

    【讨论】:

      【解决方案3】:

      如果您真的知道/想要始终返回一行,您可以将您的选择更改为 select nvl(sum(amount),0)

      1. sum 确保您始终获得 1 行,因为您没有分组
      2. 如果没有找到,nvlnull 替换为 0

      请注意,如果有多个匹配行,您当然会得到所有匹配行的总和。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-02-10
        • 2021-01-24
        • 1970-01-01
        相关资源
        最近更新 更多