Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between stored procedures and user defined functions

Can anyone explain what is the exact difference between stored procedures and user defined functions, and in which context each is useful?

like image 519
vasu Avatar asked Jan 11 '10 04:01

vasu


People also ask

What is the difference between stored procedure and functions in SQL Server?

Basic DifferenceFunction must return a value but in Stored Procedure it is optional( Procedure can return zero or n values). Functions can have only input parameters for it whereas Procedures can have input/output parameters .

What is the difference between procedure vs functions?

A function would return the returning value/control to the code or calling function. The procedures perform certain tasks in a particular order on the basis of the given inputs. A procedure, on the other hand, would return the control, but would not return any value to the calling function or the code.

What is the difference between procedures and functions in SQL?

A procedure is compiled once and can be called multiple times without being compiled. A function returns a value and control to calling function or code. A procedure returns the control but not any value to calling function or code. A procedure has support for try-catch blocks.

Are stored procedures user defined?

User defined stored procedures are created by database developers or database administrators. These SPs contains one more more SQL statements to select, update, or delete records from database tables. User defined stored procedure can take input parameters and return output parameters.


1 Answers

This is what i always keep in mind :)

  • Procedure can return zero or n values whereas 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 can not be utilized in a select statement whereas function can be embedded in a select statement.
  • UDF can be used in the SQL statements anywhere in the WHERE/HAVING/SELECT section where as 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 though of as views that take parameters and can be used in JOINs and other Rowset operations.

Source http://www.codeproject.com/Tips/286539/Difference-between-stored-procedure-and-function

like image 55
Singleton Avatar answered Oct 06 '22 11:10

Singleton