PL/SQL之--函数

一、函数

   函数是作为数据库对象存储在oracle数据库中,函数又被称为PL/SQL子程序。oracle处理使用系统提供的函数之外,用户还可以自己定义函数。函数通常被作为一个表达式来调用或存储过程的一个参数,具有返回值。通常用于返回特定的数据。 函数语法如下:

create or replace function 函数名称 (
  参数名称 测试类型,
  参数名称 测试类型
)
return 数据类型
is
自定义变量名 数据类型
begin
  处理语句;
  return 自定义变量名;
  exception
  异常处理语句;
end;

  函数和存储过程类似,只是函数必须有返回值。

二、实例

1、没有参数的函数

create or replace function test 
return varchar2
is 
begin
       return 'hello world';
end test;
-- 函数调用 
begin
   dbms_output.put_line(test());
end

2、有输入参数的函数

create or replace function get_name(
  v_id number
) 
return varchar2
is --is类似于declare
  v_name varchar2(50);     
begin
  select username into v_name from person where id = v_id;
  return v_name;
end get_name;
-- 函数调用 
begin 
   dbms_output.put_line(get_name(1));
end;

3、有带输入和输出的函数

create or replace function get_perons_info(
    f_id number,
    f_age out number
)
return varchar2
is
    v_name varchar2(50); --必须有声明长度
begin
    select username, age into v_name, f_age from person where id = f_id;
    return v_name;
end get_perons_info;
-- 函数调用
declare
    v_age number;
    v_name varchar2(255);
begin
    v_name := get_perons_info(1, v_age );
    dbms_output.put_line('name:'||v_name||' age:'||v_age);
end;

 4、带有输入输出参数的函数

create or replace function get_person_info2(
    f_id in out number    
)
return varchar2
is
    v_name varchar2(50);
begin
    select username, age into v_name, f_id from person where id = f_id;
    return v_name;
end get_person_info2;
-- 函数调用 
declare
    v_id    number;
    v_name varchar2(50);
begin
    v_id := 1;
    v_name := get_person_info2(v_id);
    dbms_output.put_line('name:'||v_name||' age:'||v_id );
end;

 5、函数返回游标

create or replace function get_person_all
  return sys_refcursor
is
    p_cursor sys_refcursor;
begin
    open p_cursor for
      select *  from person;  
     return p_cursor;
  exception
         when others then
           DBMS_OUTPUT.PUT_LINE('获取信息发生错误');
end get_person_all; 
--函数调用
declare
    c_cursor sys_refcursor;
    r_person person%rowtype;
begin
  c_cursor := get_person_all();
  --2、打开游标
--  open c_cursor; --此处不需要显示地打开游标,因为调用存储过程的时候返回的游标已经打开了
  --3、提取数据
  loop
    fetch c_cursor 
    into r_person;
    exit when c_cursor%notfound; -- 下面没有数据的时候,退出
    dbms_output.put_line('id:'||r_person.id);
    dbms_output.put_line('username:'||r_person.username);
    dbms_output.put_line('age:'||r_person.age); 
  end loop; 
end;

 三、函数其他命令

  重新编译函数

alter function 函数名称 compile; 

  删除函数

drop function 函数名称;

  查看指定的函数

select * from dba_objects where object_name = '函数名称(字母大写)' and object_type ='FUNCTION';

posted on 2014-10-11 21:21  烟火_  阅读(572)  评论(0编辑  收藏  举报

导航