Recently I gave an inetrview in which the interviewer asked me to explain the most basic difference between Stored Procedure and UDF's.
I was able to recall a couple of differences as listed here but he didn't accept any of them as the BASIC difference.
Answer according to him was that SP's are only compiled once while UDF's are compiled everytime they are called resulting in UDF's being considerably slower than stored procedure.
Now I have searched but couldn't get a clear cut answer whether this assertion is true. Please verify this.
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 biggest advantage of stored procedures is that they're compiled into the database, thus allowing high-speed processing.
The function must return a value but in Stored Procedure it is optional. Even a procedure can return zero or n values. Functions can have only input parameters for it whereas Procedures can have input or output parameters. Functions can be called from Procedure whereas Procedures cannot be called from a Function.
In a function, it is mandatory to use the RETURNS and RETURN arguments, whereas in a stored procedure is not necessary. In few words, a stored procedure is more flexible to write any code that you want, while functions have a rigid structure and functionality.
@mhasan, thanks for referring to my blog-post in your question.
As far a I know Stored Procedures & Functions both have same behavior in terms of compilation & recompilation. Both are not pre-compiled. When you create either one of them they are just parsed and created, but not compiled. Both are compiled when they are executed for the first time. And they could be re-compiled automatically again if there is any change applied to them.
Execute following query after you create a new function:
SELECT objtype, cacheobjtype, usecounts, text
FROM sys.dm_exec_cached_plans AS p
CROSS APPLY sys.dm_exec_sql_text(p.plan_handle) AS t
WHERE t.text LIKE '%YourNewFunctionName%'
You will see only one record, which is the Compiled plan of for this query itself, i.e. an Adhoc Object-Type.
After executing the function rre-execute this query again. You will see more records including the Compiled plan of the Function, which has an Object-Type of Proc.
Hope this helps.
That's a odd statement and as far I know UDF and SP are compiled (and recompiled when it changes) alike. It appear you interviewer mixed UDF with dynamic (non parametric) queries. If someone find a slight info to sustain that argument please report it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With