04 July 2014

Difference between a Function and a Stored Procedure

UDF can be used inline in SQL statements anywhere in the WHERE/HAVING/SELECT section, whereas Stored procedures cannot be. UDFs that return tables can be treated as another rowset. This can be used in JOINs with other tables. Inline UDF’s can be thought of as views that take parameters.




  • Procedure can return zero or n values whereas scalar-function can return one value which is mandatory.

  • Procedures can have input/output parameters for it whereas functions can have only input parameters.

  • Procedure allows select as well as DML statement in it whereas function allows only select statement in it.

  • Functions can be called from procedure whereas procedures cannot be called from function.

  • Exception can be handled by try-catch block in a procedure whereas try-catch block cannot be used in a function.

  • We can go for transaction management in procedure whereas we can't go in function.

  • Procedures cannot be utilized in a select statement whereas function can be embedded in a select statement.

  • UDF can have upto 1023 input parameters, Stored Procedure can have upto 21000 input parameters


Functions are computed values and cannot perform permanent environmental changes to SQL Server (i.e. no INSERT or UPDATE statements allowed). It returns error like “Invalid use of a side-effecting operator 'INSERT' within a function.”


Sometimes we face a question, why we can't execute stored procedure inside a function?
Answer:
1. Stored Procedure may contain DML statements.
2. Function can't contain DML statements.
So executing Function inside stored procedure will never break rule 1.
But executing stored procedure inside function may break rule no 2.

No comments: