咱们来定义一个oracle的函数oracle
create or replace function 方法名(参数名1 参数类型,参数名2 参数类型,参数名3 参数类型)return 返回类型 is num_C number; --定义变量 begin --处理函数的过程-- --返回结果 return num_C; end;
如:咱们来建立一个处理加、减、乘、除的计算函数函数
/*** **** *** 说明:建立一个加法、减法、乘法、除法的计算函数 ** 参数:num_A 数字型参数A,num_B 数字型参数B,numType 计算类型 ** 返回:数字类型 ****/ create or replace function fun_Test(num_A number,num_B number,numType number)return number is num_C number; --定义变量 begin --计算类型为1 时,表示进行加法运算--- if numType = 1 then num_C := num_A + num_B; end if; --计算类型为2 时,表示进行减法运算--- if numType=2 then num_C := num_A - num_B; end if; --计算类型为3 时,表示进行乘法运算--- if numType=3 then num_C := num_A * num_B; end if; --计算类型为4 时,表示进行除法运算--- if numType=4 then num_C := num_A/num_B; end if; --输出结果 dbms_output.put_line('输出值:'|| num_C); return num_C; end;
上面的处理函数用的if end if,也可用if elsif else end if进行处理(注意 不是else if ,是elsif)spa
if numType=1 then num_C := num_A + num_B; elsif numType=2 then num_C := num_A - num_B; elsif numType=3 then num_C := num_A * num_B; elsif numType=4 then num_C := num_A / num_B; else --其它处理 end if;
执行建立后,可在数据的函数文件下看到3d
那么怎么调用咱们建立的计算函数呢?code
--执行加法运算-- select fun_Test(1,3,1) 结果 from dual; --执行减法运算-- select fun_Test(8,3,2) 结果 from dual; --执行乘法运算-- select fun_Test(4,3,3) 结果 from dual; --执行除法运算-- select fun_Test(6,3,4) 结果 from dual;
也能够一块儿调用blog
--执行加法、减法、乘法、除反运算-- select fun_Test(1,3,1) 结果1,fun_Test(8,3,2) 结果2,fun_Test(4,3,3) 结果3,fun_Test(6,3,4) 结果4 from dual;
结果以下字符串
附录一个生成单号函数方法io
create or replace function fun_DxcWorkNo(prefix varchar2,singStr varchar2,billType integer)return varchar2 is billNo varchar(20); nowDate varchar(20); begin --获取单号的当前年月日时分秒 190412090428 --- select to_char(Sysdate,'yyMMddHHmmss') into nowDate from dual; --组成单号的字符串 Rw190412090428_1--- billNo:= prefix || nowDate || singStr|| billType; return billNo; end;
注意事项:function
1) 若是函数的参数是字符串,那边它的数据类型是varchar2,而不是varchar2(20)class
2) 函数定义的返回类型是什么类型,就得return 什么类型
3)若是包含if 判断,记得是if-elsif 不是 if-else if