函数

------------------------------------------------函数 begin---------------------------------
22. 函数的 helloworld: 返回一个 "helloworld--!" 的字符串

create or replace function helloworld
return varchar2
is
begin
       return 'helloworld--!';
end;


执行函数


begin
    dbms_output.put_line(helloworld());
end;

23. 定义带参数的函数: 两个数相加

create or replace function add_func(a number, b number)
return number
is
begin
       return (a + b);
end;

执行函数

begin
    dbms_output.put_line(add_func(12, 13));
end;

25. 定义一个函数: 获取给定部门的工资总和, 要求, 部门号定义为参数, 工资总额定义为返回值.

create or replace function sum_sal(dept_id number)
       return number
       is
       
       cursor sal_cursor is select salary from employees where department_id = dept_id;
       v_sum_sal number(8) := 0;   
begin
       for c in sal_cursor loop
           v_sum_sal := v_sum_sal + c.salary;
       end loop;       


       dbms_output.put_line('sum salary: ' || v_sum_sal);
       return v_sum_sal;
end;

执行函数

begin
    dbms_output.put_line(sum_sal(80));
end;

26. 关于 OUT 型的参数: 因为函数只能有一个返回值, PL/SQL 程序可以通过 OUT 型的参数实现有多个返回值
要求: 定义一个函数: 获取给定部门的工资总和 和 该部门的员工总数, 要求: 部门号定义为参数, 工资总额定义为返回值.

create or replace function sum_sal(dept_id number, total_count out number)
       return number
       is
       
       cursor sal_cursor is select salary from employees where department_id = dept_id;
       v_sum_sal number(8) := 0;   
begin
       total_count := 0;


       for c in sal_cursor loop
           v_sum_sal := v_sum_sal + c.salary;
           total_count := total_count + 1;
       end loop;       


       --dbms_output.put_line('sum salary: ' || v_sum_sal);
       return v_sum_sal;
end;   

执行函数:

declare 
  v_total number(3) := 0;


begin
    dbms_output.put_line(sum_sal(80, v_total));
    dbms_output.put_line(v_total);
end;

------------------------------------------------函数 end---------------------------------

原文地址:https://www.cnblogs.com/nbkyzms/p/5031430.html