1. Syntax format
Create [or replace] [(parameter,...) ]return datatypeas| is (local declarations) begin statement; return return_values; end name;
2. Create a function named Annual_comp to return the annual salary by receiving two variables (one employee's monthly salary pi_sal and bonus Pi_comm). Null processing is required in this function (i.e., wages and bonuses are treated as 0 if they are null).
(1) Create and invoke the function Annual_comp, passing the values of the payroll and Bonus columns, which allow nulls, but the function should still be able to return a non-empty annual salary. Use the formula defined below: annual salary = (Salary *12) + bonus
(2) required to display all employee number, name, salary, bonus and annual salary of department number 20th (annual call function obtained).
Sql> Create or Replace functionAnnual_comp2(Pi_sal Number, Pi_comm Number) 3 return Number 4 as 5Annual_sal Number; 6 begin 7Annual_sal:=NVL (Pi_sal,0)* A+NVL (Pi_comm,0); 8 returnannual_sal; 9 EndAnnual_comp;Ten /The function has been created. SQL> SelectEmpno,ename,sal,comm,annual_comp (Sal,comm)2 fromEMP3 whereDeptno= -; EMPNO ename SAL COMM annual_comp (sal,comm)---------- ---------- ---------- ---------- --------------------- 7369SMITH - 9600 7566JONES2975 35700 7788SCOTT the 36000 7876Adams1100 13200 7902FORD the 36000
Attention:
? function parameters: only in Parameters
The function can have multiple return statements, but executes a return statement
3. Ways to use functions
? Assigns the return value of a function to a variable or global variable
? using in the SELECT statement
4. Syntax for deleting functions
Drop function function_name;
5. Create a function named Valid_deptno, known as the department number, to determine if the department exists with the Dept Department table.
Sql> Create or Replace functionValid_deptno2(V_deptno Dept.deptno%type)3 returnBoolean4 as 5V_count Number; 6 begin 7 Select Count(*) intoV_count fromDeptwhereDeptno=V_deptno; 8 ifV_count=0 Then 9 returnfalse;Ten Else One returntrue; A End if; - End; - /The function has been created. SQL> Declare 2Flag Boolean; 3 begin 4Flag=Valid_deptno (4); 5 ifFlag Then 6Dbms_output.put_line ('the sector exists'); 7 Else 8Dbms_output.put_line ('The department does not exist'); 9 End if; Ten End; One /the department exists PL/The SQL process has completed successfully. SQL> Declare 2Flag Boolean; 3 begin 4Flag=Valid_deptno ( -); 5 ifFlag Then 6Dbms_output.put_line ('the sector exists'); 7 Else 8Dbms_output.put_line ('The department does not exist'); 9 End if; Ten End; One /there is no PL in this department/The SQL process has completed successfully.
oracle--function