oracle函数中可为null的返回类型
是否可以从oracle函数返回null 我具有以下oracle功能:oracle函数中可为null的返回类型,oracle,function,plsqldeveloper,Oracle,Function,Plsqldeveloper,是否可以从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 GetAm
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:未找到数据
在这种情况下,我希望函数返回null。如果您确实知道/希望始终返回一行,您可以将select更改为
select nvl(总和(金额),0)
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;
sum
确保始终得到1行,因为您没有分组nvl
如果未找到任何内容,则将null
替换为0
当然,请注意,如果有多个匹配行,您将得到所有匹配行的总和。当您在PL/SQL中执行非批量隐式游标时(这是您使用
选择…进入…
所做的),您必须记住它至少需要一行,最多需要一行
如果您得到的行数少于或多于1行,您将得到一个异常-要么找不到数据,要么太多行,这两种情况都是不言自明的
如果您希望代码在出现任何一个异常时执行某些操作,那么您将需要处理这些异常
例如:
select语句返回的代码失败的行不止一行,这不是因为它返回0行。如果它返回了0行,则返回值为null。否,如果它返回了0行,则您将获得No_data_found异常。尝试运行此操作,选择amount from salary,其中salary.month=:并查看结果@Rene现在帖子没问题了,否则前面的错误指向我在最初的评论中说的对不起,在PL/SQL Developer中重新测试后,
ORA-01403:no data found
异常被抛出。我已经纠正了我的问题。
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;