Stored Functions

We can use these user defined functions to return some values by computing the data in the database. but we cannot change the database using any stored function.

These functions must return a value,only have input parameters,should be compiled and executed each time when we want to call the function and can use inside the stored procedures as well.

We’ll look at the format of a Stored Function.

CREATE FUNCTION functionName (

@para1 varchar(50),@para2 varchar(50) )


RETURN (SELECT @para1 + ' '+ @para2)

FROM emp;


It doesn’t have many changes of the format with compared to the Stored Procedures.I hope you got it.

So i’ll show some examples how we can use these functions for our systems.

  • A salary calculator

CREATE FUNCTION calc_salary (@id varchar) 

declare @hrs_worked int
declare @rate float 
declare @amt float

SELECT @rate = e.rate, @hrs_worked = e.hrs_worked

FROM emp e
WHERE = @id
SET @amt = @rate * @hrs_worked
RETURN @amt end;

You can do any mathematical operations or whatever the things you want to the data in the database and return as you can see in the above example.Not a big deal 🙂

So you can call the written function like this.

<div class="page" title="Page 5">
<div class="section">
<div class="layoutArea">
<div class="column">

declare @salary float
exec @salary = calc_salary 'e001'

print @salary


So that’s it basically about stored functions.Please let me know if you any queries regarding any of these 🙂

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s