stored procedure Vs Functions - Sql Server

May 02, 2019 BY xtreme

Both stored procedures and functions are database objects which contain a set of SQL statements to complete a task.

Stored Procedures are pre-compiled objects which are compiled for the first time and its compiled format is saved, 
which executes (compiled code) whenever it is called. 
SQL Server compiles each Stored Procedure once and then reutilizes the execution plan. This results in tremendous 
performance boosts when Stored Procedures are called repeatedly.

A function is compiled and executed every time whenever it is called. A function must return a value and cannot 
modify the data received as parameters. 

1. The function must return a value but in SProc it is optional. Even a procedure can return zero or n values.
2. Functions can have only input parameters for it whereas Procedures can have input or output parameters.
3. Functions can be called from Procedure whereas Procedures cannot be called from a Function.
4. The procedure allows SELECT as well as DML(INSERT/UPDATE/DELETE) statement in it whereas Function allows  
   only SELECT statement in it.
5. Procedures cannot be utilized in a SELECT statement whereas Function can be embedded in a SELECT statement.
6. Stored Procedures cannot be used in the SQL statements WHERE/HAVING/SELECT section whereas Function can be.
7. An exception can be handled by try-catch block in a Sproc whereas try-catch block cannot be used in a Function.
8. We can use Transactions in Procedure whereas we can't use Transactions in Function