I've been learning Functions and Stored Procedure for quite a while but I don't know why and when I should use a function or a stored procedure. They look same to me, maybe because I am kinda newbie about that.
Can some one tell me why?
I've been learning Functions and Stored Procedure for quite a while but I don't know why and when I should use a function or a stored procedure. They look same to me, maybe because I am kinda newbie about that.
Can some one tell me why?
In SQL Server, functions and stored procedure are two different types of entities.
Function: In SQL Server database, the functions are used to perform some actions and the action returns a result immediately. Functions are two types:
System defined
User defined
Stored Procedures: In SQL Server, the stored procedures are stored in server and it can be return zero, single and multiple values. Stored Procedures are two types:
Stored Procedures are used as scripts. They run series of commands for you and you can schedule them to run at certain times.
Functions are used as methods. You pass it something and it returns a result. Should be small and fast - does it on the fly.
Stored procedure:
EXEC
orEXECUTE
statement.OUT
parameter.Function:
Can only be used to select records. However, it can be called very easily from within standard SQL, such as:
or
For simple reusable select operations, functions can simplify code. Just be wary of using
JOIN
clauses in your functions. If your function has aJOIN
clause and you call it from another select statement that returns multiple results, that function call willJOIN
those tables together for each line returned in the result set. So though they can be helpful in simplifying some logic, they can also be a performance bottleneck if they're not used properly.OUT
parameter.Functions are computed values and cannot perform permanent environmental changes to SQL Server (i.e. no INSERT or UPDATE statements allowed).
A function can be used inline in SQL statements if it returns a scalar value, or can be joined upon if it returns a result set.
A point worth noting from comments, which summarize the answer. Thanks to @Sean K Anderson:
a User Defined Function is an important tool available to a sql server programmer. You can use it inline in a SQL statement like so
where
lookupValue
will be an UDF. This kind of functionality is not possible when using a stored procedure. At the same time you cannot do certain things inside a UDF. The basic thing to remember here is that UDF's:a stored procedure can do those things.
For me the inline usage of a UDF is the most important usage of a UDF.