Tuesday, October 30, 2007

SQL Server: Function vs Stored Procedure

Functions are referred as UDF (User Defined Functions) in SQL Server. There where no UDF till SQL Server 7.0. UDF was first introduced in SQL Server 2000.

Some of the difference between UDF and Stored procedure given in SQL Magazine are as follows:

1) A UDF must return a value-a single result set. A stored procedure can return a value-or even multiple result sets-but doesn't have to.

2) You can use a UDF directly in a SELECT statement as well as in ORDER BY, WHERE, and FROM clauses, but you can't use a stored procedure in a SELECT statement.

3) A UDF can't use a nondeterministic function such as GETDATE(), NEWID(), or RAND(), whereas a stored procedure can use such functions. A nondeterministic function is one that can return a different result given the same input parameters.

4) A UDF can't change server environment variables; a stored procedure can.

5) A UDF always stops execution of T-SQL code when an error occurs, whereas a stored procedure continues to the next instruction if you've used proper error handling code.