Technical Articles

Difference between Stored Procedure and Function in SQL Server?

0 0
Stored Procedures are pre-compile 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.

Basic Difference

  1. Function must return a value but in Stored Procedure it is optional( Procedure can return zero or n values).
  2. Functions can have only input parameters for it whereas Procedures can have input/output parameters .
  3. Function takes one input parameter it is mandatory but Stored Procedure may take o to n input parameters..
  4. Functions can be called from Procedure whereas Procedures cannot be called from Function.

Advance Difference

  1. Procedure allows SELECT as well as DML(INSERT/UPDATE/DELETE) statement in it whereas Function allows only SELECT statement in it.
  2. Procedures can not be utilized in a SELECT statement whereas Function can be embedded in a SELECT statement.
  3. Stored Procedures cannot be used in the SQL statements anywhere in the WHERE/HAVING/SELECT section whereas Function can be.
  4. Functions that return tables can be treated as another rowset. This can be used in JOINs with other tables.
  5. Inline Function can be though of as views that take parameters and can be used in JOINs and other Rowset operations.
  6. Exception can be handled by try-catch block in a Procedure whereas try-catch block cannot be used in a Function.
  7. We can go for Transaction Management in Procedure whereas we can’t go in Function.
Stored Procedure
Functions
Compilation
Stored in database in compiled format.
Note: Compiled indicates, Execution plan will be made by sql at the time it created and stored in DB.
Will compiled at run time
Return type
It can directly return only integers
Return type is not must
It can return any scalar or table
Return type is must
Multiple return values
It can also return more than one values (of any data type) indirectly with the help of out parameters
It won’t support out parameters
DML Statements
Can have DML statements.
Cannot have DML statements.
Note: In case of multi-table valued functions it can contain DML statements affecting Table Variables.
Execution
Stored procedure can execute function.
Cannot be the part of Select query as a column.
Stored Procedures cannot be used in the SQL statements anywhere in the WHERE/HAVING/SELECT
Function cannot execute stored procedure.
Can be the part of select query as a column.
Functions be used in the SQL statements anywhere in the WHERE/HAVING/SELECT
Exception handling
Can have Try….Catch
Cannot have Try….Catch
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x
× How can I help you?