Functions in SQL Server are essential components of Transact-SQL (T-SQL) that allow you to perform calculations, manipulate data, and streamline complex queries. They enable you to achieve a wide range of tasks efficiently, from simple data formatting to advanced computations and logic.
Functions in SQL Server are reusable code blocks that accept input parameters, process them, and return a result. Functions enhance modularity, simplify complex logic, and make code reusable and maintainable.
SQL Server provides two primary categories of functions:
Built-in functions provided by SQL Server to handle common operations like calculations, string manipulations, and date/time processing.
Custom functions created by users to implement specific logic not covered by system functions.
These return a single value and can be used wherever an expression is allowed.
SELECT LEN('SQL Server') AS Length;
'SQL Server'
.
Length
------
10
These operate on a set of values and return a single aggregated value.
SELECT AVG(salary) AS AverageSalary FROM employees;
salary
column.Output: For salaries 5000, 7000, 9000
:
AverageSalary
-------------
7000
Used to assign a rank to rows within a result set.
SELECT name, salary, RANK() OVER (ORDER BY salary DESC) AS Rank FROM employees;
Output: For salaries 9000, 7000, 5000
:
name salary Rank
----- ------- ----
Alice 9000 1
Bob 7000 2
Charlie 5000 3
Used for manipulating string data.
SELECT CONCAT(first_name, ' ', last_name) AS FullName FROM employees;
first_name
and last_name
with a space in between.Output: For first_name = 'John'
, last_name = 'Doe'
:
FullName
--------
John Doe
Allow operations on date and time values.
SELECT GETDATE() AS CurrentDateTime;
CurrentDateTime
---------------
2024-11-12 14:45:30.000
Used to convert data from one type to another.
SELECT CAST(123.456 AS INT) AS ConvertedValue;
123.456
to an integer.
ConvertedValue
--------------
123
UDFs allow users to define custom logic.
Returns a single value.
CREATE FUNCTION CalculateTax(@amount FLOAT)
RETURNS FLOAT
AS
BEGIN
RETURN @amount * 0.10;
END;
SELECT dbo.CalculateTax(1000) AS Tax;
Tax
---
100.0
Returns a table and is defined with a single SELECT
statement.
CREATE FUNCTION GetHighSalaryEmployees()
RETURNS TABLE
AS
RETURN
(
SELECT name, salary FROM employees WHERE salary > 7000
);
SELECT * FROM dbo.GetHighSalaryEmployees();
Output: For employees
with salaries 5000, 7000, 9000
:
name salary
----- ------
Alice 9000
Returns a table but allows multiple statements for processing.
CREATE FUNCTION GetEmployeesByDepartment(@dept_id INT)
RETURNS @Result TABLE (name NVARCHAR(50), salary FLOAT)
AS
BEGIN
INSERT INTO @Result
SELECT name, salary FROM employees WHERE department_id = @dept_id;
RETURN;
END;
SELECT * FROM dbo.GetEmployeesByDepartment(1);
name salary
----- ------
John 5000
Jane 7000
SELECT
UPPER(SUBSTRING(name, 1, 3)) AS ShortName,
ROUND(salary, 2) AS RoundedSalary,
GETDATE() AS QueryDate
FROM employees;
ShortName RoundedSalary QueryDate
---------- ------------- -----------------------
JOH 5000.00 2024-11-12 14:50:45.000
JAN 7000.00 2024-11-12 14:50:45.000
SELECT LEN(CONCAT(first_name, ' ', last_name)) AS NameLength FROM employees;
SELECT * FROM employees WHERE ROUND(salary, -3) = 5000;
Functions in SQL Server are powerful tools that enhance data processing and simplify complex queries. Whether you're using built-in system functions or creating your own UDFs, understanding their capabilities will make you a more effective SQL developer. Happy Coding!❤️