Paramclasses Academy - Blog

Tutorials Details

←
Post 27 of 40
→

# SQL Server User-Defined Functions: Scalar and Table-Valued Functions with Examples

# SQL Server User-Defined Functions: Scalar and Table-Valued Functions with Examples

November 18, 2026

???? SQL Server User-Defined Functions: Scalar and Table-Valued Functions

???? Introduction to User-Defined Functions in SQL Server

A User-Defined Function (UDF) in Microsoft SQL Server is a reusable database object that accepts input parameters, performs a specific operation, and returns a result.

Functions help developers organize SQL logic and reuse calculations or data-retrieval operations without writing the same logic repeatedly.

For example, suppose you are developing an Employee Management System. You may need to:

  • Calculate an employee's annual salary.

  • Calculate tax or discount amounts.

  • Retrieve employees belonging to a particular department.

  • Calculate the average salary of employees.

  • Return filtered employee records.

Instead of writing the same logic repeatedly, you can create a User-Defined Function and call it whenever required.

SQL Server mainly supports two important types of user-defined functions:

  1. Scalar-Valued Function

  2. Table-Valued Function

At Param Classes, students learn SQL Server concepts through practical examples and real-world database operations.


???? What You Will Learn

After completing this tutorial, you will understand:

  1. What is a User-Defined Function in SQL Server?

  2. Why do we use User-Defined Functions?

  3. Types of User-Defined Functions.

  4. What is a Scalar-Valued Function?

  5. How to create and execute Scalar Functions.

  6. What is a Table-Valued Function?

  7. Inline Table-Valued Functions.

  8. Multi-Statement Table-Valued Functions.

  9. How to modify and delete functions.

  10. Difference between Scalar and Table-Valued Functions.

  11. Difference between Functions and Stored Procedures.

  12. Practical SQL Server examples.


???? 1. What Is a User-Defined Function in SQL Server?

A User-Defined Function is a custom function created by a developer to perform a particular task and return a value or table.

SQL Server provides built-in functions such as:

  • GETDATE() – Returns the current date and time.

  • LEN() – Returns the length of a string.

  • SUM() – Calculates the total of numeric values.

  • AVG() – Calculates the average value.

  • UPPER() – Converts text into uppercase.

Apart from built-in functions, developers can create their own functions using the CREATE FUNCTION statement.

Example:

CREATE FUNCTION dbo.CalculateBonus
(
    @Salary DECIMAL(10,2)
)
RETURNS DECIMAL(10,2)
AS
BEGIN
    RETURN @Salary * 0.10;
END;
GO

This function calculates 10% of the supplied salary and returns a single numeric value.

To call the function:

SELECT dbo.CalculateBonus(50000) AS BonusAmount;

Expected Output:

BonusAmount
5000.00

???? 2. Types of User-Defined Functions in SQL Server

SQL Server supports two main types of Transact-SQL User-Defined Functions.

Function Type Description
Scalar-Valued Function Returns one single value.
Table-Valued Function Returns a table containing rows and columns.

Table-Valued Functions are further divided into:

1. Inline Table-Valued Function (Inline TVF)

Returns a table using a single SELECT statement.

2. Multi-Statement Table-Valued Function (Multi-Statement TVF)

Returns a table through a table variable that can be populated using multiple statements.


???? 3. What Is a Scalar-Valued Function?

A Scalar-Valued Function returns only one value, such as:

  • INT

  • VARCHAR

  • DECIMAL

  • DATE

  • DATETIME

It is useful when you need to perform calculations or return a single result.

Real-World Examples:

  • Calculate employee bonuses.

  • Calculate annual salary.

  • Calculate product discounts.

  • Convert text into a required format.

  • Calculate age or other values.

Basic Syntax of Scalar Function

CREATE FUNCTION FunctionName
(
    @ParameterName DataType
)
RETURNS ReturnDataType
AS
BEGIN

    -- SQL Statements

    RETURN Value;

END;
GO

Explanation:

Keyword Description
CREATE FUNCTION Creates a new function.
FunctionName Name of the function.
@ParameterName Input parameter.
RETURNS Defines the return data type.
BEGIN Starts the function body.
RETURN Returns a single value.
END Ends the function.

???? 4. Create a Database and Employees Table

Let's understand SQL Server Functions through a practical Employee Management System.

Step 1: Create a Database

CREATE DATABASE FunctionDB;
GO

USE FunctionDB;
GO

Step 2: Create an Employees Table

CREATE TABLE Employees
(
    EmployeeID INT PRIMARY KEY IDENTITY(1,1),
    EmployeeName VARCHAR(100),
    Department VARCHAR(50),
    Salary DECIMAL(10,2)
);
GO

Step 3: Insert Sample Records

INSERT INTO Employees
(EmployeeName, Department, Salary)
VALUES
('Rahul', 'IT', 35000),
('Amit', 'HR', 30000),
('Priya', 'IT', 45000),
('Neha', 'Finance', 40000),
('Rohit', 'Marketing', 32000);
GO

Step 4: Display Employee Records

SELECT * FROM Employees;

Expected Output:

EmployeeID EmployeeName Department Salary
1 Rahul IT 35000
2 Amit HR 30000
3 Priya IT 45000
4 Neha Finance 40000
5 Rohit Marketing 32000

Our EmployeeDB-style example table is now ready inside FunctionDB.


???? 5. Create Your First Scalar-Valued Function

Let's create a function that calculates the annual salary of an employee.

Step 1: Create the Function

CREATE FUNCTION dbo.CalculateAnnualSalary
(
    @MonthlySalary DECIMAL(10,2)
)
RETURNS DECIMAL(12,2)
AS
BEGIN

    DECLARE @AnnualSalary DECIMAL(12,2);

    SET @AnnualSalary = @MonthlySalary * 12;

    RETURN @AnnualSalary;

END;
GO

Step 2: Execute the Function

SELECT dbo.CalculateAnnualSalary(35000)
AS AnnualSalary;

Expected Output:

AnnualSalary
420000.00

Explanation:

  • @MonthlySalary accepts the monthly salary.

  • RETURNS DECIMAL(12,2) defines the returned value's data type.

  • DECLARE creates a local variable.

  • SET assigns the calculated annual salary.

  • RETURN sends the result back.

Important: A scalar function is commonly called inside a SELECT statement using its function name and parameters.


???? 6. Scalar Function Using Employee Table

Now let's create a function that calculates the annual salary of a particular employee using EmployeeID.

CREATE FUNCTION dbo.GetEmployeeAnnualSalary
(
    @EmployeeID INT
)
RETURNS DECIMAL(12,2)
AS
BEGIN

    DECLARE @AnnualSalary DECIMAL(12,2);

    SELECT @AnnualSalary = Salary * 12
    FROM Employees
    WHERE EmployeeID = @EmployeeID;

    RETURN @AnnualSalary;

END;
GO

Execute the Function

SELECT dbo.GetEmployeeAnnualSalary(1)
AS AnnualSalary;

Expected Output:

AnnualSalary
420000.00

Use the Function with SELECT

You can also call the function for every employee.

SELECT
    EmployeeID,
    EmployeeName,
    Salary,
    dbo.GetEmployeeAnnualSalary(EmployeeID)
    AS AnnualSalary
FROM Employees;

Expected Output:

EmployeeID EmployeeName Salary AnnualSalary
1 Rahul 35000 420000
2 Amit 30000 360000
3 Priya 45000 540000
4 Neha 40000 480000
5 Rohit 32000 384000

This is a practical example of using a Scalar-Valued Function with table records.


???? 7. Scalar Function with Multiple Parameters

A Scalar Function can accept multiple input parameters.

Let's create a function to calculate a product's discount amount.

CREATE FUNCTION dbo.CalculateDiscount
(
    @Price DECIMAL(10,2),
    @DiscountPercentage DECIMAL(5,2)
)
RETURNS DECIMAL(10,2)
AS
BEGIN

    DECLARE @DiscountAmount DECIMAL(10,2);

    SET @DiscountAmount =
        @Price * @DiscountPercentage / 100;

    RETURN @DiscountAmount;

END;
GO

Execute the Function

SELECT dbo.CalculateDiscount(5000, 10)
AS DiscountAmount;

Expected Output:

DiscountAmount
500.00

Calculate Final Price

SELECT
    5000 AS OriginalPrice,
    dbo.CalculateDiscount(5000, 10) AS Discount,
    5000 - dbo.CalculateDiscount(5000, 10)
    AS FinalPrice;

Expected Output:

OriginalPrice Discount FinalPrice
5000 500 4500

???? 8. What Is a Table-Valued Function?

A Table-Valued Function (TVF) is a user-defined function that returns a table containing multiple rows and columns.

Unlike Scalar Functions, which return a single value, Table-Valued Functions return a complete table result.

Real-World Examples:

  • Retrieve employees from a specific department.

  • Display products belonging to a category.

  • Retrieve students according to their course.

  • Display orders for a particular customer.

  • Filter records using input parameters.

Basic Syntax

CREATE FUNCTION FunctionName
(
    @ParameterName DataType
)
RETURNS TABLE
AS
RETURN
(
    SELECT Column1, Column2
    FROM TableName
    WHERE Condition
);
GO

Important: A Table-Valued Function is generally used in the FROM clause, just like a table or view.


???? 9. Inline Table-Valued Function (Inline TVF)

An Inline Table-Valued Function returns a table using a single SELECT statement.

Let's create a function that retrieves employees belonging to a particular department.

Step 1: Create the Function

CREATE FUNCTION dbo.GetEmployeesByDepartment
(
    @Department VARCHAR(50)
)
RETURNS TABLE
AS
RETURN
(
    SELECT
        EmployeeID,
        EmployeeName,
        Department,
        Salary
    FROM Employees
    WHERE Department = @Department
);
GO

Step 2: Execute the Function

SELECT *
FROM dbo.GetEmployeesByDepartment('IT');

Expected Output:

EmployeeID EmployeeName Department Salary
1 Rahul IT 35000
3 Priya IT 45000

Another Example

SELECT *
FROM dbo.GetEmployeesByDepartment('HR');

This returns employees working in the HR department.

Use TVF with WHERE Condition

SELECT *
FROM dbo.GetEmployeesByDepartment('IT')
WHERE Salary > 40000;

Expected Output:

EmployeeID EmployeeName Department Salary
3 Priya IT 45000

Remember: Inline TVFs are useful when you want to return a filtered result set that can also participate in other SQL queries.


???? 10. Multi-Statement Table-Valued Function

A Multi-Statement Table-Valued Function returns a table through a table variable.

Unlike an Inline TVF, it allows multiple statements to prepare and populate the returned table.

Basic Syntax

CREATE FUNCTION FunctionName
(
    @ParameterName DataType
)
RETURNS @Result TABLE
(
    Column1 DataType,
    Column2 DataType
)
AS
BEGIN

    -- Multiple SQL Statements

    RETURN;

END;
GO

Practical Example

Let's create a function that returns employees whose salary is greater than or equal to a given amount.

Step 1: Create the Function

CREATE FUNCTION dbo.GetHighSalaryEmployees
(
    @MinimumSalary DECIMAL(10,2)
)
RETURNS @EmployeeResult TABLE
(
    EmployeeID INT,
    EmployeeName VARCHAR(100),
    Department VARCHAR(50),
    Salary DECIMAL(10,2)
)
AS
BEGIN

    INSERT INTO @EmployeeResult
    (
        EmployeeID,
        EmployeeName,
        Department,
        Salary
    )
    SELECT
        EmployeeID,
        EmployeeName,
        Department,
        Salary
    FROM Employees
    WHERE Salary >= @MinimumSalary;

    RETURN;

END;
GO

Step 2: Execute the Function

SELECT *
FROM dbo.GetHighSalaryEmployees(35000);

Expected Output:

EmployeeID EmployeeName Department Salary
1 Rahul IT 35000
3 Priya IT 45000
4 Neha Finance 40000

Explanation:

  • RETURNS @EmployeeResult TABLE defines the returned table variable.

  • INSERT INTO @EmployeeResult inserts matching records into the return table.

  • RETURN returns the populated table.

  • The function accepts a minimum salary as an input parameter.


???? 11. Difference Between Inline and Multi-Statement Table-Valued Functions

Feature Inline TVF Multi-Statement TVF
Return Type Table Table variable
SELECT Statements One SELECT defines the result Can use multiple statements
Table Variable Not explicitly declared Declared in RETURNS
Logic Simpler More flexible
Usage Simple filtering and joins More complex result preparation

Tip: Prefer an Inline TVF when the required result can be expressed with one SELECT statement. Use a Multi-Statement TVF when you need multiple steps to build the result.


???? 12. Using Table-Valued Functions with JOIN

A Table-Valued Function can also be used with other tables through JOIN operations.

Let's create a Department table.

CREATE TABLE Departments
(
    DepartmentID INT PRIMARY KEY,
    DepartmentName VARCHAR(50)
);
GO

Insert sample departments:

INSERT INTO Departments
(DepartmentID, DepartmentName)
VALUES
(1, 'IT'),
(2, 'HR'),
(3, 'Finance'),
(4, 'Marketing');
GO

Now use the department function with a JOIN:

SELECT
    E.EmployeeID,
    E.EmployeeName,
    E.Department,
    E.Salary,
    D.DepartmentID
FROM dbo.GetEmployeesByDepartment('IT') AS E
INNER JOIN Departments AS D
    ON E.Department = D.DepartmentName;

This query returns IT employees along with their matching department information.


???? 13. How to Modify a User-Defined Function Using ALTER FUNCTION

If you want to modify an existing function, SQL Server provides the ALTER FUNCTION statement.

Let's update our annual salary function.

ALTER FUNCTION dbo.CalculateAnnualSalary
(
    @MonthlySalary DECIMAL(10,2)
)
RETURNS DECIMAL(12,2)
AS
BEGIN

    RETURN @MonthlySalary * 12;

END;
GO

Execute the Modified Function

SELECT dbo.CalculateAnnualSalary(40000)
AS AnnualSalary;

Expected Output:

AnnualSalary
480000.00

Important: ALTER FUNCTION modifies an existing function. It does not create a new function.

You cannot use ALTER FUNCTION to change a Scalar Function into a Table-Valued Function or vice versa. Such a change requires a different function definition.


???? 14. How to Delete a User-Defined Function

If a function is no longer required, you can delete it using DROP FUNCTION.

Delete a Scalar Function

DROP FUNCTION dbo.CalculateAnnualSalary;
GO

Delete a Table-Valued Function

DROP FUNCTION dbo.GetEmployeesByDepartment;
GO

Avoid Error When Function Does Not Exist

DROP FUNCTION IF EXISTS dbo.CalculateAnnualSalary;
GO

Important: Dropping a function removes the function definition. It does not delete the records from the Employees table.


???? 15. Important Rules and Limitations of SQL Server Functions

SQL Server User-Defined Functions have certain restrictions.

Important limitations:

  1. A function cannot directly modify permanent database tables using INSERT, UPDATE or DELETE.

  2. A function cannot execute a Stored Procedure.

  3. A function cannot use TRY...CATCH error handling blocks.

  4. A function cannot use dynamic SQL.

  5. A function cannot use temporary tables.

  6. A function cannot return multiple result sets.

  7. User-Defined Functions do not support OUTPUT parameters.

  8. Table variables can be used inside functions.

  9. A function must return the value or table defined by its RETURNS clause.

Important: A Multi-Statement Table-Valued Function can insert records into its own returned table variable. This does not mean it can insert records into a permanent database table.

For operations that modify permanent data, use a Stored Procedure or another appropriate SQL statement.


???? 16. Difference Between Scalar Function and Table-Valued Function

Feature Scalar Function Table-Valued Function
Return Value Single value Table
Output One result Multiple rows and columns
RETURNS Data type such as INT or DECIMAL TABLE
Execution SELECT dbo.FunctionName() SELECT * FROM dbo.FunctionName()
Main Purpose Calculations and single-value operations Retrieving filtered records
Example CalculateAnnualSalary GetEmployeesByDepartment

Example of Scalar Function:

SELECT dbo.CalculateAnnualSalary(35000)
AS AnnualSalary;

Example of Table-Valued Function:

SELECT *
FROM dbo.GetEmployeesByDepartment('IT');

???? 17. Difference Between Stored Procedure and User-Defined Function

Stored Procedures and Functions are both important database objects, but they serve different purposes.

Feature Stored Procedure User-Defined Function
Creation CREATE PROCEDURE CREATE FUNCTION
Execution EXEC or EXECUTE Used in SELECT or FROM
Return Can return result sets and status values Must return a scalar value or table
Data Modification Can modify permanent tables Cannot directly modify permanent tables
OUTPUT Parameters Supported Not supported
TRY...CATCH Supported Not supported
Dynamic SQL Can be used Not allowed in T-SQL UDFs
Main Purpose Perform database operations Calculate or return reusable values and tables

When should you use a Stored Procedure?

Use a Stored Procedure when you need to perform INSERT, UPDATE, DELETE operations, execute multiple database operations, or handle procedural workflows.

When should you use a Function?

Use a Function when you need to calculate a value or return a table that can be used inside another SQL query.


???? 18. How to View Functions in SQL Server Management Studio (SSMS)

You can view your created functions in SQL Server Management Studio.

Follow these steps:

  1. Open SQL Server Management Studio (SSMS).

  2. Connect to your SQL Server instance.

  3. Expand the Databases folder.

  4. Select your database, such as FunctionDB.

  5. Expand the Programmability folder.

  6. Expand the Functions folder.

  7. Open Scalar-valued Functions to view Scalar Functions.

  8. Open Table-valued Functions to view Table-Valued Functions.

You can also view user-defined functions using:

SELECT
    name,
    type_desc,
    create_date,
    modify_date
FROM sys.objects
WHERE type IN ('FN', 'IF', 'TF')
ORDER BY name;

Here:

  • FN represents a SQL Scalar Function.

  • IF represents an Inline Table-Valued Function.

  • TF represents a Multi-Statement Table-Valued Function.


???? 19. Best Practices for SQL Server User-Defined Functions

Follow these best practices when creating functions:

  1. Use Meaningful Names: Use names such as CalculateAnnualSalary and GetEmployeesByDepartment.

  2. Choose the Correct Function Type: Use Scalar Functions for single values and TVFs for table results.

  3. Use Appropriate Data Types: Select suitable data types and sizes for parameters and return values.

  4. Keep Functions Simple: Avoid unnecessary calculations and complicated logic.

  5. Avoid Unnecessary Function Calls: Repeated scalar function calls over large datasets can affect query performance.

  6. Prefer Inline TVFs Where Suitable: They often provide the optimizer with more flexibility than multi-statement TVFs.

  7. Test Different Inputs: Test valid, invalid, boundary and unmatched parameter values.

  8. Use Schema Names: Use names such as dbo.CalculateAnnualSalary.

  9. Check Dependencies: Before modifying or dropping a function, check whether other database objects depend on it.


???? 20. Frequently Asked Questions (FAQs)

Q1. What is a User-Defined Function in SQL Server?

A User-Defined Function is a custom database object that accepts input parameters, performs an operation and returns a scalar value or table.

Q2. What are the two main types of User-Defined Functions?

The two main types are Scalar-Valued Functions and Table-Valued Functions.

Q3. What is a Scalar-Valued Function?

A Scalar-Valued Function returns a single value such as INT, VARCHAR, DECIMAL or DATE.

Q4. What is a Table-Valued Function?

A Table-Valued Function returns a table containing multiple rows and columns.

Q5. What are the types of Table-Valued Functions?

There are two common T-SQL types: Inline Table-Valued Functions and Multi-Statement Table-Valued Functions.

Q6. Which command is used to create a function?

The CREATE FUNCTION statement is used to create a User-Defined Function.

Q7. How do you call a Scalar Function?

A Scalar Function can be called inside a SELECT statement.

Example:

SELECT dbo.CalculateAnnualSalary(35000);

Q8. How do you call a Table-Valued Function?

A Table-Valued Function is generally called in the FROM clause.

Example:

SELECT *
FROM dbo.GetEmployeesByDepartment('IT');

Q9. Can a SQL Server Function modify a permanent table?

No. A T-SQL User-Defined Function cannot directly modify permanent database tables.

Q10. Can a Function accept multiple parameters?

Yes. A User-Defined Function can accept multiple input parameters.

Q11. Can a Function return multiple values?

A Scalar Function returns one scalar value. A Table-Valued Function can return multiple rows and columns.

Q12. What is the difference between a Function and a Stored Procedure?

A Function must return a scalar value or table and can be used within SQL queries. A Stored Procedure is executed using EXEC and can perform database modification operations.


???? Conclusion

In this tutorial, we learned SQL Server User-Defined Functions step by step with practical examples.

We covered Scalar-Valued Functions, Inline Table-Valued Functions, Multi-Statement Table-Valued Functions, Function Parameters, CREATE FUNCTION, ALTER FUNCTION and DROP FUNCTION.

We also understood how functions can be used with SELECT statements, WHERE conditions and JOIN operations.

User-Defined Functions are an important part of SQL Server development because they help developers create reusable calculations and data-retrieval logic.

At Param Classes, we focus on practical SQL Server training so students can understand database concepts and apply them in real-world projects.

Keep Learning, Keep Practicing, and Build Your SQL Server Development Skills with Param Classes!


???? Practical Assignment

Create a Student Management Database and complete the following tasks:

  1. Create a Students table with StudentID, StudentName, Course and Fees columns.

  2. Insert at least five student records.

  3. Create a Scalar Function to calculate a 10% discount on course fees.

  4. Create a Scalar Function to calculate the final course fees after discount.

  5. Create an Inline Table-Valued Function to retrieve students by course.

  6. Create a Multi-Statement Table-Valued Function to return students whose fees are greater than a specified amount.

  7. Execute all functions and verify the results.

  8. Modify one function using ALTER FUNCTION.

  9. Delete one function using DROP FUNCTION.

Learning Goal: Practice creating and executing SQL Server Functions independently using SQL Server Management Studio.

←
Post 27 of 40
→