Posted on 2008-10-27 11:12
sailor 阅读(366)
评论(0) 编辑 收藏 所属分类:
oracle
一、定义
函数用于返回特定的数据。如果在应用程序中经常需要通过执行SQL语句来返回特定的数据,那么可以基于这些操作建立特定的函数。
二、语法
语法
1create or replace function fun_name(Name in type, Name in type, ) return varchar2 is
2 varName varchar2;
3begin
4
5 return(varName);
6end fun_name;
注意:当建立函数时,函数头部一定要有返回类型,函数执行体一定要有return语句。
三、例子
1、简历函数,不带任何参数
no arg
1create or replace function stat_dept_noarg
2return NUMBER is
3v_count NUMBER(3,0);
4BEGIN
5 dbms_output.put_line('统计部门人数');
6 select count(empno) into v_count from emp
7 where depno=1;
8 return v_count;
9END;
10/
11
12SQL> set serveroutput on
13SQL> exec dbms_output.put_line(stat_dept_noarg);
2、建立函数,带有IN参数
arg
1create or replace function stat_dept(v_no NUMBER)
2return NUMBER is
3v_count NUMBER(3,0);
4BEGIN
5 dbms_output.put_line('统计部门人数');
6 select count(empno) into v_count from emp
7 where depno=v_no;
8 return v_count;
9END;
10/
调用
1select stat_dept(2) from dual;
2
3或者
4
5var dno NUMBER
6exec :dno := stat_dept(2);
3、建立函数,带有参数out
带有参数out
1create or replace function dept_out(v_no NUMBER,v_dname OUT VARCHAR)
2return VARCHAR2 is
3 v_desc VARCHAR2(200);
4BEGIN
5 dbms_output.put_line('查看部门消息');
6 select dname,description into v_dname,v_desc from dept where depno = v_no;
7 return v_desc;
8END;
9/
10
11SQL> var result varchar2
12SQL> exec :result := dept_out(1,:name);
4、建立函数,同时带有参数in、out
1SQL> create or replace function show_dept_withinout(v_no in out number, v_name in OUT varchar2)
2 2 return VARCHAR2 is
3 3 v_desc VARCHAR2(30);
4 4 begin
5 5 select dname, description INto v_name, v_desc from dept where depno = v_no;
6 6 return v_desc;
7 7 end;
8 8 /
9
10Function created
11
12SQL> var num number
13SQL> var name varchar2
14SQL> var desc varchar2
15SQL> exec :num := 9
16
17PL/SQL procedure successfully completed
18num
19---------
209
21
22SQL> exec :name := 'IT部门'
23
24PL/SQL procedure successfully completed
25name
26---------
27IT部门
28
29SQL> exec :desc := show_dept_withinout(:num, :name);
30
31PL/SQL procedure successfully completed
32desc
33---------
34
35num
36---------
379
38name
39---------
40IT部门
四、查看函数
1SQL>select text from user_source where name = 'FUNCTION_NAME'