Original address: https://blog.csdn.net/libertine1993/article/details/47264211
The syntax of an Oracle custom function is as follows:
- create or replace function function name (parameter 1 mode parameter type)
- return return value type
- as
- variable1 variable type;
- variable2 variable type;
- begin
- function body;
- end function name;
There are 3 modes of parameters: (If not specified, the default type of the parameter is in.)
in : read-only mode, in the function, the value of the parameter can only be referenced and cannot be changed;
out : In write-only mode, it can only be assigned, not referenced;
in out : Readable and writable.
Reminder:
1. In Oracle custom functions, the correct way to write else if is elsif instead of else if
2. To use if, you need to add then "if condition then operation"
Simple example: read in two values, return the larger value
- create or replace function function1(para1 in number, para2 in number)
- return number
- as
- begin
- if para1 > para2 then
- return para1;
- else
- return para2;
- end if;
- end function1;
use:
- select function1(666, 333) from dual;
result:
Another example may be used in practice. Sometimes we need to perform data statistics by non-natural months. In this case, we only need to write a custom function to process the date.
Function description: Read in date type date, those greater than the 15th are included in the next month, those less than or equal to the 15th are included in this month
- create or replace function fn_mymonth(oridate in date)
- return varchar2
- as
- oriday number;
- orimonth number;
- oriyear number;
- begin
- oriday := to_number(to_char(oridate, 'dd'));
- orimonth := to_number(to_char(oridate, 'mm'));
- oriyear := to_number(to_char(oridate, 'yyyy'));
- if oriday <= 15 then -- less than or equal to the 15th belongs to this month
- return to_char(oridate, 'yyyymm');
- else
- if orimonth <= 8 then -- day <= 8, then after +1, turn to char and make up 0, which is used separately as a case
- return to_char (oriyear) || '0' || to_char (orimonth + 1);
- elsif( orimonth <= 11 ) then -- day <= 11, then +1 will not cross the new year, and it is not necessary to fill in zeros when converting to char, and it is separated as a case
- return to_char (oriyear) || to_char (orimonth + 1);
- else -- the last case is a new year, change the year, just fill the month with zeros
- return to_char (oriyear + 1) || '0' || to_char (orimonth - 11);
- end if;
- end if;
- end fn_mymonth;
Use and results:
- select fn_mymonth(to_date('2015-12-14', 'yyyy-mm-dd')) from dual;
- select fn_mymonth(to_date('2015-12-15', 'yyyy-mm-dd')) from dual;
- select fn_mymonth(to_date('2015-12-16', 'yyyy-mm-dd')) from dual;