Search code examples
sql-serverperformancestored-proceduresfunction

performance difference between User Defined Function and Stored Procedures


If a statement return rows doing a simple select over the data base, is there performance difference between implement it using Function and Procedures? I know it is preferable to do it using function, but it is really faster?


Solution

  • There is no difference in speed between a query run inside a function and one run inside a procedure.

    Stored procedures have problems aggregating results, they cannot be composed with other stored procedures. The only solution is really cumbersome as it involves catching the procedure output into a table with INSERT ... EXEC ... and then using the resulted table.

    Functions have the advantage of being highly composable as a table value function can be placed anywhere a table expression is expected (FROM, JOIN, APPLY, IN etc). But functions have some very severe limitations in terms of what is permitted in a function and what is not, exactly because they can appear anywhere in a query.

    So it is really apple to oranges. The decision is not driven by performance, but by requirements. As a general rule anything that returns a dataset should be a view or a table valued function. Anything that manipulates data must be a procedure.