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;
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章