Friday 12 April 2013

What is difference between stored procedure and function

Stored Procedure :
  • Procedure need not to return a value.
  • Procedure returns values using output parameters
  • procedure can't be called in select statement.
  • use procedure to update the salary of the employee.
     syntax :   
                       create|alter procedure<name>[parameters] (here parameters are optional)
                        as
                         begin
                         statements
                           end
          Example:
                      create|alter proc addnum(@x int,@y int)
                       as
                      begin
                        declare @z int 
                        print @z
                        end
      execution:  execute addnum @x=10,@y=20
Function :
  • Function must returns a value.
  • Function returns values using return statement.
  • Function called in select statement.
  • use  function to calculate the employee annual salary.
          syntax 1:
                             create function<name>[parameters]    (This is Scalar valued Syntax)
                                returns<type>
                              as 
                                begin
                                  statements
                                   end
            Example:
                                 create function addnum(@x int ,@y int)
                                 returns int
                                  as
                                  begin
                                  return(@x+@y)
                                  end


                       execution
                                           select dbo.addnum(10,20)
                                                             (or)
                                            declare @k int
                                           set @k=dbo.addnum(10,20)
                                           print @k


              syntax 2 :       
                                create function<name>[parameters]    (This is table valued Syntax)
                                returns table
                              as 
                                begin
                                 return (select statement)
                                   end   
                            
             Example:
                                  create function getemp(@d int)
                                   returns table
                                  as
                                 return(select * from emp where dept=@d)
               execution
                                    select * from dbo.getemp(10)

No comments:

Post a Comment