Oracle:PL*Plus编程(四)

本文详细介绍了数据库编程中的核心概念,包括函数、包和触发器的创建、调用及管理方法。通过具体实例展示了如何使用这些特性来增强数据库应用程序的功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

函数

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

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;
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值