语法:
CREATE OR REPLACE FUNCTION[( )] RETURN IS [declare section] BEGIN [ ] RETURN ; [EXCEPTION ];
例子:
create or replace function fun_sk(n positive) return positive is hon varchar2(23):='hongda'; //有警告,可以用,变量就是这么声明的
ho number:=23;
h number; begin if(n=1) then return 1; else return n*fun_sk(n-1); end if; //注意if,比sqlserver中多了then,最后还要 end if; end;
select fun_sk(3) from dual; //调用
Oracle的function中与procedure的区别
1.function的参数不需要in/out,它全部的是输入参数
2.声明了返回类型 return positive
3.必须要有返回 return ...
4.输入的参数不能同列名相同,编译不会出错,运行会报错。(procedure也有这个问题)
create or replace function fun_num(country varchar2) return number is people number; begin select people into people from tb where country=country; return people; exception when no_data_found then return 0; when others then return -1; end fun_num; 这个方法运行错误
运行正确的:
create or replace function fun_num(country2 varchar2) return number is people number; //变量可以同列名相同 begin select people into people from tb where country=country2; return people; exception //异常处理 when no_data_found then return 0; when others then return -1; end fun_num;
select fun_num('中国') from dual; //当tb中有两行中国的行时,会返回-1
修改:
create or replace function fun_num(country2 varchar2) return number is people2 number; begin select people into people2 from tb where country=country2 and rownum<=1; //oracle没有top,但有一个隐藏序列rownum return people2; exception when no_data_found then return 0; when others then return -1; end fun_num;
斐波那契
create or replace function fun_fi(n pls_integer)
return pls_integer
is
begin
if(n=1) then
return 1;
elsif(n=2) then //oracle杂种啊,这是elsif,不是elseif,搞死我了才发现
return 1;
else
return fun_fi(n-2)+fun_fi(n-1);
end if;
end;
pls_integer可以存储一个有符号的整形值,其精度范围和BINARY_INTEGER一样,是:-2^31~2^31。
PLS_INTEGER和NUMBER比较起来,其优点是:
1).占有较少的存储空间;
2).可以直接进行算术运算(在NUMBER上不能直接进行算术运算,如果要计算,NUMBER必须先被转换成二进制)。所以在进行算术的时候PLS_INTEGER比NUMBER和BINARY_INTEGER快一些。
PLS_INTEGER和BINARY_INTEGER区别:
PLS_INTEGER进行的运算发生溢出的时候,会触发异常。但是当BINARY_INTEGER运算发生溢出时,如果可以指派给一个NUMBER变量(没有超出NUMBER的精度范围)的话就不会触发异常
create or replace function GEN_MERACCOUNTID(v_tradecode in varchar2) return varchar2 As v_result varchar2(10); begin SELECT v_tradecode||lpad(SEQ_MERCHANTACCOUNTID.nextval, 9, '0') into v_result FROM DUAL; return v_result; end GEN_MERACCOUNTID;
select GEN_MERACCOUNTID('6') into accountid from sys.dual;
http://www.cnblogs.com/luxh/archive/2012/08/15/2639832.html