SQL Server Functions
There are two kinds of Functions in SQL Server. A Function in SQL Server is a named set of SQL explanations that can be called and executed as a solitary unit. The function can perform estimations, control information, and return scalar or table-based results.
1. Scalar function
A Function capability returns a solitary worth, like a whole number, float, or string. Scalar capabilities are utilized inside SQL articulations, such as SELECT or WHERE statements, to perform computations or alter information.
Here is an illustration of a scalar Function that returns the length of a string,
CREATE FUNCTION fnStringLength (@str VARCHAR(50))
RETURNS INT
AS
BEGIN
DECLARE @length INT
SET @length = LEN(@str)
RETURN @length
END
2. Table-valued functions
A table-valued function returns a table as its result set. Table-valued functions are often used to encapsulate complex queries and simplify their use in other parts of the database.
Here is an example of a table-valued function that returns a table of employees who have a salary greater than a specified amount,
CREATE FUNCTION fnGetHighSalaryEmployees (@salary FLOAT)
RETURNS TABLE
AS
RETURN (
SELECT * FROM Employees WHERE Salary > @salary
)
Functions can be created using the CREATE FUNCTION statement and called using the SELECT statement or within other SQL statements. It's important to note that functions can significantly impact performance, so it's essential to use them judiciously and test their performance in real-world scenarios.