Skip to main content

Functions - SQL Server

 Functions

In SQL Server, a function is a pre-written piece of code that performs a specific task and returns a value. Functions can be used to encapsulate complex calculations, to improve performance by reducing network traffic, and to enforce security by restricting direct access to database tables.

There are two types of functions in SQL Server:

1.     Scalar Functions: These functions return a single value based on input parameters. Examples include LEN, which returns the length of a string, and SUM, which returns the sum of a set of values.

2.     Table-Valued Functions: These functions return a table or a set of rows based on input parameters. Examples include fnSplit, which splits a string into rows based on a delimiter, and fnGetSalesByMonth, which returns sales data grouped by month.

To create a function in SQL Server, you can use the CREATE FUNCTION statement. Here's an example of creating a scalar function:

CREATE FUNCTION GetTotalOrders

(

    @CustomerID int

)

RETURNS int

AS

BEGIN

    DECLARE @TotalOrders int;

    SELECT @TotalOrders = COUNT(*) FROM Orders WHERE CustomerID = @CustomerID;

    RETURN @TotalOrders;

END

In this example, we're creating a scalar function called GetTotalOrders that takes an input parameter called @CustomerID and returns an integer value. The function uses a SELECT statement to count the number of orders for the specified customer ID and stores the result in a variable called @TotalOrders. Finally, the function returns the value of @TotalOrders.

Here's an example of creating a table-valued function:

CREATE FUNCTION fnGetSalesByMonth

(

    @Year int

)

RETURNS TABLE

AS

RETURN

(

    SELECT MONTH(OrderDate) AS Month, SUM(TotalAmount) AS TotalSales

    FROM Orders

    WHERE YEAR(OrderDate) = @Year

    GROUP BY MONTH(OrderDate)

)

 

In this example, we're creating a table-valued function called fnGetSalesByMonth that takes an input parameter called @Year and returns a table with two columns: Month and TotalSales. The function uses a SELECT statement to retrieve sales data for the specified year, grouping the data by month and calculating the total sales for each month.

Once you've created the function, you can call it like any other function. For example:

SELECT dbo.GetTotalOrders(12345);

 In this example, we're calling the GetTotalOrders function with an input parameter of 12345. The function will return the total number of orders for the

specified customer ID.

Reference :

            https://learn.microsoft.com/en-us/sql/t-sql/statements/create-function-transact-sql?view=sql-server-ver16

Comments

Popular posts from this blog

Data type precedence - SQL Server

       In SQL Server, data type precedence determines which data type takes precedence over others when two or more data types are combined or compared. It is important to understand data type precedence to ensure that the correct data type is used and that data is not lost or truncated during operations. In this blog, we will discuss data type precedence in SQL Server with examples. Data type precedence levels SQL Server has 16 data type precedence levels, with the highest level being 1 and the lowest level being 16. The data type with the lowest precedence is considered to be the "weakest" data type and is most likely to be converted to a higher precedence data type during operations. Here is the list of data types in SQL Server, ordered by their precedence levels: user-defined data types (highest precedence) sql_variant xml datetimeoffset datetime2 datetime smalldatetime date time float real decimal/numeric money/smallmoney bigint/i...

Synonyms, Trigger & Sequences - SQL Server

  Synonyms In SQL Server, a synonym is an alternative name for a database object, such as a table, view, stored procedure, or function. Synonyms can be useful for simplifying complex object names, abstracting the underlying object structure, or providing a layer of indirection between objects and their callers. Creating a synonym in SQL Server is straightforward. Here's an example:               CREATE SYNONYM MyTable FOR AdventureWorks2019 . dbo . MyTable ; In this example, we're creating a synonym called MyTable that points to a table called MyTable in the AdventureWorks2019 database. Now, instead of referring to the table as AdventureWorks2019.dbo.MyTable, we can simply use the synonym name MyTable. To modify a synonym in SQL Server, you can use the ALTER SYNONYM statement. Here's an example:               ALTER SYNONYM MyTable RENA...

Table Data Type- SQL Server

       In SQL Server, the table data type is a structured data type that allows you to define a table as a variable. It can be useful in scenarios where you need to store data temporarily or pass data between stored procedures or functions. In this blog, we will explore the table data type in SQL Server and provide an example of how it can be used. Introduction to the table data type The table data type is a structured data type that allows you to define a table as a variable. It can be used to store data temporarily or pass data between stored procedures or functions. The table variable behaves like a regular table in SQL Server, but it is stored in memory rather than on disk. Creating a table variable in SQL Server To create a table variable in SQL Server, you need to declare the variable and define the table structure. The following code demonstrates how to declare a table variable and define the table structure: DECLARE @MyTable TABLE (   ...