Skip to main content

Sql Server Functions

Function 

Function is a database object in Sql Server. Basically it is a set of sql statements that accepts only input arameters, perform actions and return the result. Function can return only single value or a table. We can’t use function to Insert, Update, Delete records in the database table(s).Generally two types of functions are available in sql server these are System Defined Function , another is User defined Funtion. 

Types of Function

  1. System Defined Function

SDF are built in function in Sql Server. User defined function are two types are Scalar Function and Aggregate Function.These functions are defined by Sql Server for different purpose.

                  01.Scalar Function

                    Scalar functions operates on a single value and returns a single value. Below is the list of some                        useful Sql Server Scalar functions.

Scalar Function
Description
abs(-10.67)
This returns absolute number of the given number means 10.67.
rand(10)
This will generate random number of 10 characters.
round(17.56719,3)
This will round off the given number to 3 places of decimal means 17.567
upper('dotnet')
This will returns upper case of given string means 'DOTNET'
lower('DOTNET')
This will returns lower case of given string means 'dotnet'
ltrim(' dotnet')
This will remove the spaces from left hand side of 'dotnet' string.
convert(int, 15.56)
This will convert the given float value to integer means 15.

         02. Aggregate Function

                            Aggregate functions operates on a collection of values and returns a single value. Below is the list of some                             useful Sql Server Aggregate functions.
System Aggregate Function
Aggregate Function
Description
max()
This returns maximum value from a collection of values.
min()
This returns minimum value from a collection of values.
avg()
This returns average of all values in a collection.
count()
This returns no of counts from a collection of values.

02. User Defined Function

These functions are created by user in system database or in user defined database. We three types of user defined functions.

          01. Scalar Function

                      User defined scalar function also returns single value as a result of actions perform by function.                       We return any datatype value from function.
    1. --Create a table
    2. CREATE TABLE Employee
    3. (
    4. EmpID int PRIMARY KEY,
    5. FirstName varchar(50) NULL,
    6. LastName varchar(50) NULL,
    7. Salary int NULL,
    8. Address varchar(100) NULL,
    9. )
    10. --Insert Data
    11. Insert into Employee(EmpID,FirstName,LastName,Salary,Address) Values(1,'Mohan','Chauahn',22000,'Delhi');
    12. Insert into Employee(EmpID,FirstName,LastName,Salary,Address) Values(2,'Asif','Khan',15000,'Delhi');
    13. Insert into Employee(EmpID,FirstName,LastName,Salary,Address) Values(3,'Bhuvnesh','Shakya',19000,'Noida');
    14. Insert into Employee(EmpID,FirstName,LastName,Salary,Address) Values(4,'Deepak','Kumar',19000,'Noida');
    15. --See created table
    16. Select * from Employee

  1. --Create function to get emp full name






  • Create function fnGetEmpFullName
  • (
  • @FirstName varchar(50),
  • @LastName varchar(50)
  • )
  • returns varchar(101)
  • As
  • Begin return (Select @FirstName + ' '+ @LastName);
  • end

      1. --Calling the above created function
      2. Select dbo.fnGetEmpFullName(FirstName,LastName) as Name, Salary from Employee

               02. Inline Table-Valued Function

                           User defined inline table-valued function returns a table variable as a result of actions perform                         by function. The value of table variable should be derived from a single SELECT statement.
    1. --Create function to get employees
    2. Create function fnGetEmployee()
    3. returns Table
    4. As
    5. return (Select * from Employee)
    1. --Now call the above created function
    2. Select * from fnGetEmployee()


                  03. Multi-Statement Table-Valued Function

                                     User defined multi-statement table-valued function returns a table variable as a result of actions perform                                   by function. In this a table variable must be explicitly declared and defined whose value can be derived                                     from a multiple sql statements.

    1. --Create function for EmpID,FirstName and Salary of Employee
    2. Create function fnGetMulEmployee()
    3. returns @Emp Table
    4. (
    5. EmpID int,
    6. FirstName varchar(50),
    7. Salary int
    8. )
    9. As
    10. begin
    11. Insert @Emp Select e.EmpID,e.FirstName,e.Salary from Employee e;
    12. --Now update salary of first employee
    13. update @Emp set Salary=25000 where EmpID=1;
    14. --It will update only in @Emp table not in Original Employee table
    15. return
    16. end
    1. --Now call the above created function
    2. Select * from fnGetMulEmployee()
    1. --Now see the original table. This is not affected by above function update command
    2. Select * from Employee


    Note


    1. Unlike Stored Procedure, Function returns only single value.
    2. Unlike Stored Procedure, Function accepts only input parameters.
    3. Unlike Stored Procedure, Function is not used to Insert, Update, Delete data in database table(s).
    4. Like Stored Procedure, Function can be nested up to 32 level.
    5. User Defined Function can have upto 1023 input parameters while a Stored Procedure can have upto 2100 input parameters.
    6. User Defined Function can't returns XML Data Type.
    7. User Defined Function doesn't support Exception handling.
    8. User Defined Function can call only Extended Stored Procedure.
    9. User Defined Function doesn't support set options like set ROWCOUNT etc.

    Summary

    In this article I try to explain the types of function in sql server with example. I hope after reading this article you will be aware about function in Sql Server. I would like to have feedback from my blog readers. Please post your feedback, question, or comments about this article.


    Refferences: Special thanks to Shailendra Chauhan
    http://www.dotnet-tricks.com/Tutorial/sqlserver/KY3T010412-Different-Types-of-SQL-Server-Functions.html



    Comments

    Popular posts from this blog

    Database View

    View is a database object also called a logical table. it has no psychical existence. It is not like a simple table, but is a virtual or logical table which contains columns and data from different tables (may be one or more tables). A View does not contain any data, it is a set of queries that are applied to one or more tables that is stored within the database as an object. After creating a view from some table(s), it used as a reference of those tables and when executed, it shows only those data which are already mentioned in the query during the creation of the View. Creating view Syntax: ------------------------------------------------- CREATE VIEW [View_Name] AS [ SELECT Statement] ------------------------------------ ------------- CREATE VIEW SampleView As SELECT EmpID, EmpName FROM EmpInfo -------------------------------------------------- Data retrieve from view: SELECT * FROM SampleView WHERE EmpID ='FN0009C1'     View does not modif

    Efficiently Paging Through Large Amounts of Data (PageIndex, Page Size) -SQL Server

    In this article you learn how to fetch data according PageIndex and PageSize. In web application, it is much more important to increase webform performance, loadbalance. In my development experience, some of table hold large amount of records (more than 2GB) and user need to shows records in GridView. But problem is when we select all records and loads in webforms, webform has crashed. In that case, I will simply solved with Table Variable and using Grid Page Number and Page Size. 1. Create Procedure CREATE PROCEDURE Load_Data_WithPaging @PageIndex AS INT , /*Selected Row Index of selected grid*/ @PageSize AS INT , /*Total page size of selected grid*/ @TotalRecords AS INT OUT /*used for display virtual page no*/ AS BEGIN SET NOCOUNT ON ; DECLARE @FromIndex AS INT = 0 , @ToIndex AS INT = 0 ; SET @FromIndex = (@PageIndex * @PageSize) + 1 ; /*First row no selection*/ SET @ToIndex = ((@PageIndex

    What is an Index? Explain Custered Index and Non-Clustered Index

    Index Index is a database object, which can be created on one or more columns (16 Max column combination). When creating the index will read the column(s) and forms a relevant data structure to minimize the number of data comparisons. The index will improve the performance of data retrieval and adds some overhead on data modification such as create, delete and modify. So it depends on how much data retrieval can be performed on table versus how much of DML ( Insert , Delete and Update ) operations. clustered index A clustered index is something that reorganizes the way records in the table are physically stored. Therefore a table can have only one clustered index. The leaf nodes of a clustered index contain the data pages, by which I mean the key-value pair in the clustered index has the index key and the actual data value. Also remember, a clustered index will be created on a table by default the moment a primary key is created on the table. A clustered index is so