Professional Documents
Culture Documents
3 - Stored Procedures and Functions
3 - Stored Procedures and Functions
Definition:
1
Procedure Syntax
Where:
[REPLACE] is used in case the procedure already exists in the database, and the definition of the
procedure need to be changed.
Mode: represents the type of argument (IN, OUT, IN OUT). IN is the default argument mode.
Example:
The following example demonstrates the use of procedure to insert a new department in ‘dept’
table –which is a copy of ‘department’ table of HR Schema-
2
After executing the previous example a procedure with the name ‘add_dept’ is stored in the
database as a database object.
Note:
1. When you create any object such as table, procedure, function, and so on, the entries are
made to the user_objects table.
You can check the user_objects table by issuing the following command:
3
Function Syntax
Where:
RETURN datatype: the data type of the value returned by the function.
Example:
The following example demonstrates the use of function called check_sal to check if the salary
of a particular employee is greater or less than the average salary of all employees working in his
department. The function returns TRUE if the salary of the employee is greater than the average
salary of employees in his department else returns FALSE. The function returns NULL if a
NO_DATA_FOUND exception is thrown.
4
END IF;
EXCEPTION
WHEN NO_DATA_FOUND TNEN
RETURN NULL
END;
/
The function is invoked as a part of a statement. Remember that the function check_sal returns
Boolean or NULL and therefore the call to the function is included as the conditional expression
for the IF block.
Note:
You can use the DESCRIBE command to check the argument and return type of the function.
Example:
DESCRIBE check_sal;
5
Passing Parameters to Function
DROP FUNCTION check_sal;
/
CREATE FUNCTION check_sal(empno employees.employee_id%TYPE)
RETURN Boolean IS
dept_id employees.department_id%TYPE;
sal employees.salary%TYPE;
avg_sal employees.salary%TYPE;
BEGIN
SELECT salary, department_id INTO sal,dept_id
FROM employees WHERE employee_id=empno;
SELECT avg(salary) INTO avg_sal FROM employees
WHERE department_id=dept_id;
IF sal > avg_sal THEN
RETURN TRUE;
ELSE
RETURN FALSE;
END IF;
EXCEPTION
WHEN NO_DATA_FOUND THEN
RETURN NULL;
END;
/
The previous function accepts employee number as parameter. You can now pass different
employee’s number and check for the employee’s salary.
6
ELSE
DBMS_OUTPUT.PUT_LINE('Salary < average');
END IF;
END;
/
The previous code invokes the function ‘check_sal’ twice by passing parameters. The output of
the code is as following: