SQL
Difference between Function and Stored Procedure.
In this post, we are going to learn the Difference between Function and Stored Procedure in SQL.
Function:Â Function is compiled and executed every time it is called. This cannot modify the data received as parameters and function must return a value.
Stored Procedure: Â This is a pre-compiled object as this gets compiled for the first time and its compiled format gets saved as well, which gets executed (compiled code) when it is called.
- The function must return a value but in Stored Procedure it is optional. Even a procedure can return zero or n values.
- Functions can have only input parameters for it whereas Procedures can have input or output parameters.
- Functions can be called from Procedure whereas Procedures cannot be called from a Function.
- The procedure allows SELECT as well as DML(INSERT/UPDATE/DELETE) statement in it whereas Function allows only SELECT statement in it.
- Procedures cannot be utilized in a SELECT statement whereas Function can be embedded in a SELECT statement.
- Stored Procedures cannot be used in the SQL statements anywhere in the WHERE/HAVING/SELECT section whereas Function can be.
- Functions that return tables can be treated as another rowset. This can be used in JOINs with other tables.
- Inline Function can be though of as views that take parameters and can be used in JOINs and other Rowset operations.
- An exception can be handled by try-catch block in a Procedure whereas try-catch block cannot be used in a Function.
- We can use Transactions in Procedure whereas we can’t use Transactions in Function.
Benefits of Stored Procedures
- Reduced: Stored procedures have to be executed only once and the execution code can be used again later. In this way, it impacts the final performance when you have to call the same procedure multiple times within a database application.
- Programming: It helps in cutting down the size of the code and it can be transmitted over the network quickly. Ultimately, network traffic will reduce significantly.
- Effective: The best thing is that one stored procedure can be accessed by multiple users at once. It results in the reduced development cycle and enhances the performance.
- Enhanced: Every time when you are executing a stored procedure, certain permissions can be defined that enhances the security controls.
Benefits of Function in SQL Server
- Modular Programming: Functions allow modular programming where it is generated once and called multiple times during programming.
- Faster Execution: Every time a function is called, the execution code is saved in the cache that helps in faster execution of function when it is called again.
- Reduced Network Traffic: A function utilizes the WHERE clause for reducing the overall size of the code that ultimately results in enhanced network performance.