ORACLE 自定義函數
語法結構:
CREATE [OR REPLACE] FUNCTION 函數名
(
參數1 model 類型1 [DEFAULT xx],
參數2 model 類型2 [DEFAULT xx],
參數3 model 類型3 [DEFAULT xx]
)
RETURN 返回類型
[DETERMINISTIC]
IS/AS
--聲明部分
BEGIN
--PL/SQL程序塊
END [函數名]
model 參數模式有3種
- IN: 只讀模式, 在函數中, 參數的值只能被引用, 不能被改變;
- OUT: 爲只寫模式, 只能被賦值, 不能被引用;
- IN OUT: 可讀可寫;
DETERMINISTIC: 確定性函數 函數的入參不變,則其返回結果也是一定的 , Oracle11g開始會對其參數及其返回結果進行緩存處理以提升性能。
一元計算例子:
CREATE OR REPLACE FUNCTION full_calculator(ctype IN VARCHAR2, num1 IN NUMBER, num2 IN NUMBER) RETURN NUMBER DETERMINISTIC IS
res_num NUMBER :=0;
BEGIN
if ctype = '+' then
select (num1+num2) into res_num from dual;
elsif ctype = '-' then
select (num1-num2) into res_num from dual;
elsif ctype = '*' then
select (num1*num2) into res_num from dual;
elsif ctype = '/' and num2 <> 0 then
select (num1/num2) into res_num from dual;
else
RETURN NULL;
end if;
RETURN res_num;
EXCEPTION
WHEN OTHERS THEN
RETURN NULL;
END full_calculator;
-- 測試
select full_calculator('+',4,2) from dual;