Difference between Stored Procedure and Function in SQL Server

Shailendra Chauhan  Print   2 min read  
15 Sep 2012
08 Mar 2019
Intermediate
806K

Both stored procedures and functions are database objects which contain a set of SQL statements to complete a task. In many ways, both are different from each other. In this article, we’re going to discuss the differences between stored procedures and functions.

Stored Procedures

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. For more about a stored procedure, please refer to the article Different types of Stored Procedure.

Functions

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. For more about functions, please refer to the article Different types of Functions.

Basic Differences between Stored Procedure and Function in SQL Server

  1. The function must return a value but in Stored Procedure 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.

Advance Differences between Stored Procedure and Function in SQL Server

  1. The procedure allows SELECT as well as DML(INSERT/UPDATE/DELETE) statement in it whereas Function allows only SELECT statement in it.

  2. Procedures cannot 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. An exception can be handled by try-catch block in a Procedure whereas try-catch block cannot be used in a Function.

  7. We can use Transactions in Procedure whereas we can't use Transactions in Function.

Summary

In this article, you learn the difference between Stored Procedure and Function. I hope after reading this article you will be able to understand BASIC as well as ADVANCE differences between Stored Procedure and Functions (UDF). Comments, criticism, and suggestions are always welcome.

Take our free skill tests to evaluate your skill!

In less than 5 minutes, with our skill test, you can identify your knowledge gaps and strengths.

Learn to Crack Your Technical Interview

+
+
Accept cookies and close this message