--1、自定義函數
create or replace function 函數名(參數1 參數類型1,參數2 參數類型2,……) return 返回值類型 as
begin
函數定義
end 函數名;
--實例1
select * from test1;
create or replace function getMaxTage return number as
begin
declare maxAge number;
begin
select max(tage) into maxAge from test1;
return maxAge;
end;
end getMaxTage;
--實例1調用
begin
dbms_output.put_line('表test1中年紀最大的是:'||getMaxTage());
end;
--執行動態拼接SQL語句:execute immediate sql語句……
--爲了提高數據庫效率利用函數的確定性:在return 返回類型之後,as之前添加deterministic關鍵字,前提條件是函數傳入參數
--一樣時返回相同,第二次調用函數是數據庫就用前一個計算的值,而不需要再重新計算一次.
--自定義函數+遊標
create or replace function row2column(sqlString varchar2)
return varchar2 as
begin
declare type cu_type is ref cursor;
temp_cursor cu_type;
temp_row1 varchar2(20);
temp_row2 varchar2(10);
v_result varchar2(200);
begin
open temp_cursor for sqlString;
fetch temp_cursor into temp_row1,temp_row2;
while temp_cursor%found loop
v_result := v_result || temp_row1 || ':' || temp_row2 || ';';
fetch temp_cursor into temp_row1,temp_row2;
end loop;
return v_result; --rtrim(v_result,',')
end;
end row2column;
--調用
select row2column('select tname,tage from test1 where tage >30') v_result from dual;
--2、存儲過程
create or replace procedure 存儲過程名稱(參數1 in/out 參數類型1,參數2 in/out 參數類型2,……) as
begin
存儲過程定義
end 存儲過程名稱;
--參數類型:
--in只進步出(表明in參數不能再存儲過程內部進行修改)
--out只出不進(out參數實際作爲存儲過程執行結果的出口,必須使用變量爲參數,變量的作用相當於佔位符,只是接收存儲過程內部賦值)
--in out 典型場景爲交換兩個變量值
--存儲過程添加調試測試
create or replace procedure insertTest1(tname in varchar2,tage in number,
ori_count out number,cur_count out number) as
begin
declare v_max_id number;
begin
if(tname is null or length(tname)=0)then
return;
end if;
if(tage<10 or tage>30)then
return;
end if;
select count(1) into ori_count from test1;
select max(tid) into v_max_id from test1;
insert into test1 values(v_max_id+1,tname,tage,'test1');
select count(1) into cur_count from test1;
end;
end insertTest1;
--程序包
create or replace package pkg_test as
function getMaxTage return number;
procedure insertTest1(tname in varchar2,tage in number,
ori_count out number,cur_count out number);
end pkg_test;
--
create or replace function is_date(params varchar2) return varchar2 is
d date;
begin
d:=to_date(nvl(params,''),'yyyy-mm-dd hh24:mi:ss');
return 'Y';
exception
when others then
return 'N';
end;
select is_date('20101010') from dual;