Difference between function and stored procedure

There are many difference between function and stored procedure. In this article we will discuss about the difference between function and procedures in context of SQL Server.

  • Stored Procedures are pre-compile objects which are compiled for first time and its compiled format is saved which executes (compiled code) whenever it is called.But Function is compiled and executed every time when it is called. 
  • Function must return a value but in Stored Procedure it is optional( Procedure can return zero or n values).
  • Functions can have only input parameters for it whereas Procedures can have input/output parameters .
  • Functions can be called from Procedure whereas Procedures cannot be called from Function
  • Procedure allows SELECT as well as DML(INSERT/UPDATE/DELETE) statement in it whereas Function allows only SELECT statement in it.
  • Procedures can not be utilized in a SELECT statement whereas Function can be embedded in a SELECT statement.
  • Stored Procedures cannot be used in the SQL statements anywhere in the WHERE/HAVING/SELECT section whereas Function can be.
  • The most important feature of stored procedures over function is to retention and reuse the execution plan while in case of function it will be compiled every time.
  • Functions that return tables can be treated as another rowset. This can be used in JOINs with other tables.
  • Inline Function can be though of as views that take parameters and can be used in JOINs and other Rowset operations.
  • Exception can be handled by try-catch block in a Procedure whereas try-catch block cannot be used in a Function.
  • We can go for Transaction Management in Procedure whereas we can’t go in Function.

Satya Prakash

VOIP Expert: More than 8 years of experience in Asterisk Development and Call Center operation Management. Unique Combination of Skill Set as IT, Analytics and operation management.

One thought on “Difference between function and stored procedure

  • March 11, 2015 at 5:54 pm
    Permalink

    CREATE OR REPLACE PROCEDURE my_proc
    (p_name IN VARCHAR2 := ‘John’) as begin … end

    CREATE OR REPLACE FUNCTION my_func
    (p_name IN VARCHAR2 := ‘John’) return varchar2 as begin … end
    Notice how the function has a return clause between the parameter list and the “as” keyword. This means that it is expected to have the last statement inside the body of the function read something like:

    return(my_varchar2_local_variable);
    Where my_varchar2_local_variable is some varchar2 that should be returned by that function.

Leave a Reply to Satya Prakash Cancel reply