What are the Differences Between Function and Procedure in SQL Server?
In this article, I will give information about what are the Differences Between Function and Procedure in SQL Server.
This question especially comes to mind of curious friends who are just learning SQL Server. This question may come up in job interviews. It is useful to know briefly, because in the programming world, it is more important to do something efficiently and with less resources than to do it.
- The function must always return a value. (Number, text, table etc.) but Stored Procedure is optional, it may not have a return value.
- You cannot use a try-catch construct in a function. You can use it in Stored Procedure.
- Function can only be used with Select, it doesn’t update or delete, Stored Procedure can do all CRUD(CREATE/READ/UPDATE/DELETE) operations.
- Function has only input parameters, but Stored Procedures can use both input and output parameters.
- Function can be called by Stored Procedure but Stored Procedure cannot be called by Function.
- Functions do not support Transaction constructs, but Stored Procedures do.
- Only variable table values can be used in functions, Temporary tables cannot be used. You can use both in procedures.
- Functions can be used anywhere in the WHERE/HAVING/SELECT section, while Stored Procedures cannot.
- Functions can be called and used using Select and Stored Procedures using Exec or Execute.
- We cannot use indexes in functions, they can be used in Stored Procedures.
- Trigger is not used in Functions, it can be used in Stored Procedure.
- While functions are not compiled once, Stored Procedures are compiled once and work efficiently.
- It can be used in functions with Join structure, not in Stored Procedures.
I hope it was useful.
Good luck to everyone in business and life.