Differences between Stored
Procedures and User Defined Functions (UDF) in SQL Server.
- Stored procedures are precompiled objects that can be reused. Stored procedure have many advantages:
- Precompiled: SQL server compiles the stored procedure once, store the execution plan and reuse it which save time to create execution plan each time the code runs.
- Reuse of code: Stored procedure can be used by multiple users and programs once created
- Security: You can restrict usage of stored procedure by defining execute permission to users.
- User defined functions are set of codes that accept parameters, perform and action and must return a result as a scalar value or as a result set. It cannot modify data. Function encapsulate frequently performed logic, that can be called from a Select or from a where clause.
- There are Built in functions and User defined functions. Functions has following advantages:
- Allows modular programming- It can be called number of times from a program and can be modified independently with out touching the entire program source code.
- Allow faster execution since it is precompiled.
Differences between Stored
Procedure and User Defined Function in SQL Server
|
User Defined Function |
Stored Procedure |
|
Function must return a value. |
Stored Procedure may /may not return values. |
|
Can be used only in SELECT statements, not in DML statements. |
Can be used with DML(INSERT/UPDATE/DELETE)
statements |
|
Allow only input parameters, doesn't support output parameters. |
Can have both input and output parameters. |
|
Doesn’t allow try-catch blocks. |
Allow to use Try catch blocks |
|
Transactions are not allowed within functions. |
Transactions can be implemented inside Stored Procedures. |
|
We can use only table variables; it will not allow using temporary
tables. |
Can use both table variables as well as temporary table in it. |
|
Stored Procedures can't be called from a function. |
Stored Procedures can call functions. |
|
Can be called from SELECT
statement. |
Procedures can't be called from SELECT /WHERE/HAVING clauses. |
|
A UDF can be used in join clause |
Procedures can't be used in Join clause |
Summary : Article describes the differences between Stored
procedure and UDF.
Comments
Post a Comment