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);
GetTotalOrders
function with an input parameter of 12345
. The function will return the total number of orders for the
specified customer ID.
Reference :
Comments
Post a Comment