In Microsoft SQL Server, in-built functions provide a wide range of tools for manipulating and analyzing data. This chapter explores various categories of in-built functions and their real-world use cases.
In Microsoft SQL Server, User-Defined Functions (UDFs) are custom functions that allow you to encapsulate logic and perform specific tasks. This chapter explores the creation, usage, and real-world applications of UDFs.
Scalar UDFs return a single value.
CREATE
FUNCTION CalculateDiscount(@Price
DECIMAL(10, 2),
@Discount
DECIMAL(5, 2))
RETURNS
DECIMAL(10, 2))
AS BEGIN
RETURN @Price * (1 - @Discount / 100);
END;
In this example, a scalar UDF named CalculateDiscount calculates the discounted price.
Table-Valued UDFs return a table result.
CREATE
FUNCTION GetOrdersByCustomer(@CustomerID INT)
RETURNS
TABLE AS
RETURN (
SELECT
OrderID, OrderDate
FROM
Orders
WHERE
CustomerID = @CustomerID );
This table-valued UDF, GetOrdersByCustomer, retrieves orders for a specific customer.
SELECT
OrderID, TotalAmount = dbo.CalculateDiscount(Price, 10)
FROM
OrderDetails
This query applies the CalculateDiscount scalar UDF to calculate discounted prices for products.
SELECT
o.OrderID, o.OrderDate, c.CustomerName
FROM
dbo.GetOrdersByCustomer(123)
AS
o
JOIN
Customers
AS
c
ON
o.CustomerID = c.CustomerID;
This query uses the GetOrdersByCustomer table-valued UDF to retrieve orders for a specific customer and joins them with customer details.
In Microsoft SQL Server, in-built functions provide a wide range of tools for manipulating and analyzing data. This chapter explores various categories of in-built functions and their real-world use cases.
In Microsoft SQL Server, subqueries are powerful tools that allow you to nest one query within another. This chapter explores subqueries, their use cases, and the CROSS APPLY operator for real-world scenarios.