Stored Functions
Stored Functions
also used to perform an action and returns result as a value. Function can be divided
into two types, these are
As
Begin
<Function Body>
End
Output:select dbo.fcube(3)
2) Create a function that takes an employee id and returns the salary of that
employee.
create function fsal(@eid int)
returns money
as
begin
declare @sal money
select @sal=salary from employee where empid=@eid
return @sal
end
Output:select dbo.fsal(1)
3) Create function to accept department name and return sum of salary of given
department?
CREATE FUNCTION SF3(@DNAME VARCHAR(10))
RETURNS MONEY
AS
BEGIN
DECLARE @TOTSAL MONEY
SELECT @TOTSAL=SUM(SALARY) FROM EMP E INNER JOIN DEPT D
ON E.DEPTNO=D.DEPTNO AND DNAME=@DNAME
RETURN @TOTSAL
END
SELECT dbo.SF3('SALES')
4) Create function to accept dates and returns no.of employee ?
CREATE FUNCTION SF4(@SD DATE,@ED DATE)
RETURNS INT
AS
BEGIN
DECLARE @NUMEMP INT
SELECT @NUMEMP=COUNT(*) FROM EMP WHERE
HIREDATE BETWEEN @SD AND @ED
RETURN @NUMEMP
END
SELECT dbo.SF4('1981-01-01','1981-12-31')
Output :
Select dbo.sf5(7788)
2)Table-Valued Fuction:In this case we can return a table as an output from the
function.
Syntax:
Returns <Table>
As
Ex: Create a function that accept the Address and returns the list of employee working
in given address from the table.
Ex:Create a function to get the deptno and return list of employee working in EMP and
DEPT tables.
RETURNS TABLE
AS
RETURN(SELECT E.EMPNO,E.ENAME,E.SALARY,S.LOSAL,S.HISAL,
A function must return a value where as procedure may or may not be returns a
value.
When a procedure want to return a value then we should use “OUT” parameter
whereas a function want to return a value then we use “RETURN” statement.
A procedure can have parameters of both input (with parameters) and output
(without parameters) where as a function can have only input (with parameters)
parameters only.
In procedure we can perform select, insert, update and delete operation where
as function can used only to perform select. Cannot be used to perform insert,
update and delete operations.
A procedure provides the option for to perform transaction management where
as these operations are not permitted in a function.
Procedures supporting to use exception handling mechanism but functions are
not supporting exception handling mechanism.
We call a procedure using execute command where as function are called by
using select command only