oracle函式 oracle函式建立及呼叫
CREATE [OR REPLACE] FUNCTION function_name
[ (argment [ { IN | OUT | IN OUT } ] Type ,
argment [ { IN | OUT | IN OUT } ] Type ]
RETURN return_type
{ IS | AS }
<型別.變數的說明>
BEGIN
FUNCTION_body
EXCEPTION
其它語句
END;
示例:
1) 在scott.emp表上建立一個函式deptsal,輸入引數為員工編號,返回該員工所在部門的平均工資。
(1)建立函式
create or replace function deptsal(f_deptno in number) return number
as
avgsal number;
begin
select avg(sal) into avgsal from emp where deptno=f_deptno;
return avgsal;
end;
/
(2)呼叫函式
declare
avgsal number(10,2);
begin
avgsal:=deptsal(10);
DBMS_OUTPUT.PUT_LINE('平均工資:'||avgsal);
end;
/
(3)效果圖
2) 在scott.emp表上建立一個函式deptnum,輸入部門編號,返回該部門的員工人數,並呼叫該函式。
(1)建立函式
create or replace function deptnum(f_deptno in number) return int
as
dept_count int;
begin
select count(1) into dept_count from emp where deptno=f_deptno;
return dept_count;
end;
/
(2)呼叫函式
declare
dept_count int;
begin
dept_count:=deptnum(10);
DBMS_OUTPUT.PUT_LINE('部門人數:'||dept_count);
end;
/
(3)效果圖