SQL Server BasicsWhat is SQL Server database?What is RDBMS?What is Normalization?Why we use Denormalization?What_is_SQL?What is PL/SQL?Difference between SQL and PL/SQLDatabase TableOne to One RelationshipOne to Many RelationshipMany to Many RelationshipMany to One RelationshipString Data TypesNumber Data TypesDate Data TypesOther Data TypesCreate DatabaseDrop DatabaseCreating and Managing Users in SQL ServerCreate TableAlter TableDrop TableConstraints in SQL serverPrimary KeyForeign KeyUnique KeyCandidate KeyComposite KeyDifference between primary key and candidate keyPrimary key and foreign key relationshipSurrogate KeyCascading Referential Integrity ConstraintsSelf Referential Integrity ConstraintsInsert into statementInsert multiple recordsUpdate statementDelete statementTruncate statementDifference between Delete and TruncateAlias in SQL ServerSelect statementSelect DistinctSelect TopSelect IntoNull Functions(ISNULL(),NULLIF(),COALESCE())Sub QueryIdentity ColumnSequence objectDifference between sequence and identity columnSQL Server ClausesWHERE ClauseOrder By ClauseTop N ClauseGroup By ClauseHaving ClauseDifference between Where and HavingSQL Server OperatorsArithmetic OperatorsComparison OperatorsLogical OperatorsBitwise OperatorsAny OperatorsAll OperatorsUnion OperatorsUnion All OperatorsDifference between Union and Union AllIntersect OperatorExcept OperatorDifference between Except and IntersectJoinsInner JoinLeft JoinRight JoinFull JoinSelf JoinCross JoinViewsWhat are views?Create views using SSMSIndexed ViewsComplex ViewsCheck Option in ViewCheck Encryption in ViewSchema Binding Option in ViewRead-only ViewsUpdatable ViewsAdvantages and disadvantages of viewsCreate multiple views on one tableCan we implement index on views?Can we Perform Insert, update, delete operation on views?Stored Procedure and FunctionsWhat are Stored Procedures?Why we use stored procedures?Passing parameters to Stored procedureUser-Defined FunctionsDifference between UDF and Stored procedurePre-Defined Functions@@Indentity and Scope_IndentityNULLIF, ISNULL and COALESCE

User-Defined Functions

User-defined functions (UDFs) in SQL Server are functions that are created by users to perform specific operations or calculations. These functions are defined using the Transact-SQL (T-SQL) language and can be used in SQL queries and statements, similar to built-in functions.

There are three types of user-defined functions in SQL Server:

Scalar Functions: Scalar functions return a single scalar value based on the input parameters. They can be used inline in SQL statements, such as SELECT, WHERE, or JOIN clauses, to perform calculations or transformations on individual values. Scalar functions are defined using the CREATE FUNCTION statement.

Here's an example of creating a scalar function in SQL Server:


CREATE FUNCTION dbo.CalculateTax (@Amount DECIMAL(10, 2))
RETURNS DECIMAL(10, 2)
AS
BEGIN
    DECLARE @Tax DECIMAL(10, 2);
    SET @Tax = @Amount * 0.1; -- 10% tax rate
    RETURN @Tax;
END

In this example, we're creating a scalar function named "CalculateTax" that takes an amount as an input parameter and calculates the tax amount based on a 10% tax rate. The function returns the calculated tax amount.

Table-Valued Functions: Table-valued functions return a table as a result set. They can be used in the FROM clause of a SELECT statement or joined with other tables. Table-valued functions can be of two types: inline table-valued functions and multi-statement table-valued functions.

Inline Table-Valued Functions (TVFs) are defined using the RETURNS TABLE statement and can contain a single SELECT statement. They return a table-like result set.

Here's an example of creating an inline TVF in SQL Server:


CREATE FUNCTION dbo.GetEmployeesByDepartment (@DepartmentID INT)
RETURNS TABLE
AS
RETURN
(
    SELECT EmployeeID, FirstName, LastName, Salary
    FROM Employees
    WHERE DepartmentID = @DepartmentID
)

In this example, we're creating an inline TVF named "GetEmployeesByDepartment" that takes a DepartmentID as an input parameter and returns the details of employees who belong to that department.

Multi-Statement Table-Valued Functions (TVFs) are defined using the BEGIN and END keywords and can contain multiple statements to populate the table variable that will be returned.

Aggregate Functions: Aggregate functions, as the name suggests, perform calculations on a set of values and return a single value as the result. Unlike built-in aggregate functions, user-defined aggregate functions allow for custom calculations and can be used with the GROUP BY clause. User-defined aggregate functions are defined using the CREATE AGGREGATE statement.

Here's an example of creating a user-defined aggregate function in SQL Server:


CREATE AGGREGATE dbo.Concatenate
(
    @Value NVARCHAR(MAX)
)
RETURNS NVARCHAR(MAX)
EXTERNAL NAME MyAssembly.Concatenate;

In this example, we're creating a user-defined aggregate function named "Concatenate" that concatenates multiple values into a single string. The implementation of the aggregate function is defined in an external assembly called "MyAssembly."

User-defined functions provide flexibility and reusability by allowing you to encapsulate custom logic and calculations within your database. They can simplify complex queries, improve code readability, and promote code modularity and maintainability.