function
The parameters of the function are in input parameters, and return is the output
grammar:
create [ or replace ] function function name (parameter 1 type 1, parameter 2 type 2, ...) return return value type is / as [ define variable ] begin - execute statement return result; [ exception -exception handling ] End ;
*** 1. The parameter of the function can only be in mode, you can omit in
2. When the function is declared, you must use return plus the return value type.
Note that the return value type of return only needs to tell the type, without defining the length, for example : Return varchar2;
variable: data type varchar2 (30)
3. The result of the function must be returned through return, that is, use the return result in begin;
No parameter function:
- Write a function that returns the HelloWorld - stored in the database, compile, and then run the Create or the replace function sayHello return VARCHAR2 IS - variable declarations, .... the begin - logic code - use return to return results return ' World Hello ' ; End ; - function of oracle: TO_CHAR () TO_DATE () - function call: calling the sql statement SELECT the sayHello () from Dual;
Parameterized function:
- according to the number of employees, annual calculation of the income of employees (salary + bonus) * 12 the Create or the replace function getYealSal (ENO emp.empno % of the type) return Number The IS v_sal emp.sal % of the type; v_comm emp.comm % of the type; the begin select sal, comm into v_sal, v_comm from emp where empno = eno; if v_comm is null then return v_sal * 12 ; else return (v_sal + v_comm)* 12 ; End IF ; End ; - call the SELECT E. * , GetYealSal (e.empno) annual income from emp E;
The difference between stored procedures and functions
1 ) The keywords are different: Stored procedure: procedure , function: function 2 ) The parameters in the stored procedure can have in input parameters, out output parameters, all the parameters in the function are in input parameters 3 ) The stored procedure does not determine the return value type, but You can use the out parameter to return the result. The function needs to determine the return value type. Use return to return the result. 4 ) The stored procedure is called in the pl / sql block, or exec, and the function can only be called in the sql statement