Home > SQL Server > Difference between Stored procedures and User Defined functions[UDF]

Difference between Stored procedures and User Defined functions[UDF]

The definition of stored procedure as from WIKIPEDIA

Stored procedure
A stored procedure is a program (or procedure) which is physically stored within a database. They are usually written in a proprietary database language like PL/SQL for Oracle database or PL/PgSQL for PostgreSQL. The advantage of a stored procedure is that when it is run, in response to a user request, it is run directly by the database engine, which usually runs on a separate database server. As such, it has direct access to the data it needs to manipulate and only needs to send its results back to the user, doing away with the overhead of communicating large amounts of data back and forth.

User-defined function
A user-defined function is a routine that encapsulates useful logic for use in other queries. While views are limited to a single SELECT statement, user-defined functions can have multiple SELECT statements and provide more powerful logic than is possible with views.

In SQL Server 2000
User defined functions have 3 main categories

  1. Scalar-valued function – returns a scalar value such as an integer or a timestamp. Can be used as column name in queries
  2. Inline function – can contain a single SELECT statement.
  3. Table-valued function – can contain any number of statements that populate the table variable to be returned. They become handy when you need to return a set of rows, but you can’t enclose the logic for getting this rowset in a single SELECT statement.


Differences between Stored procedure and User Defined Functions (UDF)

  1. UDF can be used in the SQL statements anywhere in the WHERE/HAVING/SELECT section where as Stored procedures cannot be.
  2. UDFs  return tables can be treated as another rowset . This can be used in JOINs with other tables.
  3. Stored Procedures are designed to return its output to the application. It can’t return a table variable although it can create a table .
  4. UDFs can’t change the server environment or your operating system environment, while a SPROC can. Operationally, when T-SQL encounters an error the function stops, while T-SQL will ignore an error in a SPROC and proceed to the next statement in your code (provided you’ve included
  5. Inline UDF’s can be though of as views that take parameters and can be used in JOINs and other Rowset operations.
Advertisement
Categories: SQL Server Tags: ,
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.