create or replace function fun_s(rn varchar2(20)) return number is r employees%rowtype;
n:=0;
begin
loop
select *
from employees e
where e.departmentid=rn;
n:=n+r.salary;
exit when n=n;
end loop;
end;调用
select d.departmentname,fun_s1(d.departmentid)
from department d;

解决方案 »

  1.   

    你的函数名fun_s,然而你调用却写的是fun_s1。
      

  2.   

    1. 函数参数只声明类型,不声明长度 fun_s(rn varchar2) 
    2. n:=0; n 没有声明类型
    3. select * from employees e where e.departmentid=rn; 没有 into 到 r 里
    4. exit when n=n; 死都退不出去,你这个根本不需要循环
    5. 没有 return .
      

  3.   

    create or replace package pack_ss1 as
    n number;
    function fun_s(r varchar2) return number;
    end;
    create or replace package body pack_ss1 as
    function fun_s1(rn varchar2) return number is r employees%rowtype;
    begin
    loop
    select * into r
    from employees e
    where e.departmentid=rn;
    n:=n+r.salary;
    exit when n=n; --为什么,不能退出LOOP,salary为空 n=n 不可以么?
    end loop;
    end:
    select d.departmentname,fun_s1(d.departmentid)--我希望把累加的salary输出。
    from department d;
      

  4.   

    select d.departmentname,back_ss1.fun_s1(d.departmentid)--我希望把累加的salary输出。
    from department d;
      

  5.   


    1. salary 为 null,n 值也为 null,在 oracle 里 null = null 的判断恒 false ,所以不会退出
    2) select d.departmentname,sum(back_ss1.fun_s1(d.departmentid)) as sal--我希望把累加的salary输出。
    from department d;
    另外对你这个函数的逻辑,我再次提一下
    函数中不需要 loop 循环,因为根本没用,因为 departmentid = rn 有以下三种情况
    1)无数据
    2)有且只有一条数据
    3)有多条数据
    1 和 2,这个就不说了,出现第 3 种情况,select * into 会报 TOO_MANY_ROWS 错误,函数无法正常执行
    这 3 种情况,无论哪种都是用不到循环的,你还是把 loop 去掉吧