views:

83

answers:

5

Can you tell me what is the need for a stored procedure when there is UDF?

+1  A: 

A procedure can run DML, a function cannot.

In general, a function is designed to be used as a part of the query, while a stored procedure is a batch of SQL statements run together implementing some business logic, possibly with different credentials.

Quassnoi
Not to mention DDL as well.
Aaronaught
`DDL` is a bad idea even in a procedure.
Quassnoi
I didn't say it was a good idea, I just said you can do it. ;)
Aaronaught
+2  A: 

Off the top of my head, a stored procedure can do the following that a UDF cannot do:

1) Modify Data

2) Return a result set to a client

3) Perform non-deterministic activity

Randy Minder
A `UDF` can return a result set and perform non-deterministic activity too. It would be a table-valued function and a non-deterministic function, respectively :)
Quassnoi
What he meant was UDFs cannot use non-deterministic functions like GetDate() etc.
Ender
If that is, in fact, what he meant, then he's still wrong. The only restriction that I am aware of regarding non-deterministic functions is that a function that uses them cannot be used in the context of a calculated column.
Daniel Pratt
@Daniel: a non-deterministic function can be used in a computed column. Such a column, however, cannot be indexed.
Quassnoi
A: 

Sprocs are used to return output to an application. A UDF returns a table variable.

JonH
No. A UDF can return a scalar result, or an inline query. A UDF does not have to return a table variable, and a Stored Procedure may return no output at all.
Aaronaught
My point was that a UDF can.
JonH
+1  A: 

A function cannot directly alter or update the database in any way, either via DML (INSERT, UPDATE, DELETE, ect) statements or DDL (CREATE TABLE, etc) statements. It also cannot do anything that might indirectly result in database modifications, such as executing ad-hoc SQL statements (of any sort) or executing stored procedures.

Daniel Pratt
+1  A: 

One key difference is that UDFs always have an output of fixed schema, stored procedures can result an arbitrary number of result sets in an arbitrary format.

Matt Whitfield