Differences Between Procedures & Function
Stored Procedures are pre- compiled objects which are compiled for first time and its compiled format is saved which executes (compiled code) whenever it is called. But Function is compiled and executed every time when it is called.
- Function must return a value but in Stored Procedure it is optional( Procedure can return zero or n values).
- Both functions and stored procedures can accept parameters. Functions can accept input parameters but can return only a single return value. Stored procedures can also accept OUTPUT parameters.
- Functions can be called from Procedure whereas Procedures cannot be called from Function.
- Procedure allows SELECT as well as DML(INSERT/UPDATE/DELETE) statement, whereas Function allows only SELECT statement in it.
- Stored Procedures cannot be used in the SQL statements anywhere in the WHERE/HAVING/SELECT section whereas Function can be.
- Exception can be handled by try-catch block in a Procedure whereas try-catch block cannot be used in a Function.
- We can go for Transaction Management in Procedure whereas we can't go in Function.
- Functions are normally used for computations where as procedures are normally used for executing business logic.
- Function returns 1 value only. Procedure can return multiple values (max 1024).
- Functions cannot alter data or objects in a server. Stored procedures can alter data and objects in database and server.
Summary
Basic Difference. Function must return a value but in Stored Procedure it is optional( Procedure can return zero or n values). Functions can have only input parameters for it whereas Procedures can have input/output parameters . Functions can be called from Procedure whereas Procedures cannot be called from Function
Syntax to create a procedure is ::
CREATE [OR REPLACE] PROCEDURE proc_name [list of parameters]
IS
Declaration section
BEGIN
Execution section
EXCEPTION
Exception section
END;
Syntax to create a function is ::
CREATE [OR REPLACE] FUNCTION function_name [parameters]
RETURN return_datatype;
IS
Declaration_section
BEGIN
Execution_section
Return return_variable;
EXCEPTION
exception section
Return return_variable;
END;