Oracle:PL*Plus编程(四)

函数

函数与过程很相似,唯一区别是函数必须向调用它的语句返回值。

1.创建函数

例如:

create function circle_area(
    p_radiu in number
)
 return number as
    v_area number;
begin
    v_area := v_pi * POWER(p_radiu, 2);
    return v_area;
end circle_area;

2.调用函数

select circle_area(2) from dual;


CIRCLE_AREA(2)
----------------- 
12.5663704

3.获取有关函数的信息

select object_name, aggregate, parallel
from user_procedures
where object='circle_area';

4.删除函数

drop function circle_area;

包可以将彼此相关的功能划分到一个自包含的单元中两个部分组成:规范和包体,规范中列出可用的过程、函数、类型和对象。规范中不包括构成这些过程和函数的代码,包体中财包含实际代码

1.创建包的规范

create package test_package as  
    TYPE v_test_cursor is ref cursor;   
fuction get_test_cursor 
return v_test_cursor;   
procedure update_test_type( 
    test_id in test.id%TYPE,    
    test_type in varchar(10) 
);
end test_package;

2.创建包体

create package body test_package as
    function get_test_cursor
    return v_test_cursor is 
    v_test_cursor1 v_test_cursor;
begin   
    open v_test_cursor1 cursor  
        select * from test; 
    return v_test_cursor1;
    end get_test_cursor;
    procedure update_test_type( 
        test_id in test.id%TYPE,    
        test_type in varchar(10) 
    ) as
    v_count integer;
begin   
    select count(*) into v_count    
    from test   
    where id = test_id;
    if v_count = 1 then 
        update test 
        set type = test_type 
        where id = test_id; 
        commit;
    end if;
exception 
    when others then 
        rollback;
    end update_test_type;
end product_package;

3.调用包中的函数和过程

select test_package.update_test_type(1, '09');

4.获取包中有关函数和过程信息

select object_name, procedure_name
from user_procedures
where object='test_package';

5.删除包

drop package test_package;

触发器

触发器适当特定的DML语句针对特定的数据表运行时,由数据库自动运行的过程。

1.触发器启动的时机

分为语句级触发器(为所有行只运行一次)和行级触发器(每一行都执行一次)区别:当update语句对某个列启动行级触发器时,这个触发器可以同时访问该列的新值和原值。

2.创建触发器

create trigger before_test_update_type
    before update of test_type on test
    for each now when (old.test_type = '01')
begin 
    dbms_output.put_line(:old.id); 
    dbms_output.put_line(:old.test_type); 
    dbms_output.put_line(:new.test_type); 
    insert into test_type_audit ( 
        id,old_test_type,new_test_type )
    values( :old.id, :old.test_type, :new.test_type ); 
end before_test_update_type;

3.启动触发器

update test set test_type = '06' where id = 1;

4.获取触发器有关信息

select * from user_triggers where trigger_name='before_test_update_type';

5.禁止和启动触发器禁止:

alter trigger before_test_update_type disable;

启用:

alter trigger before_test_update_type enable;

7.删除触发器

drop trigger before_test_update_type;
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章