100 Days of SQL

sql

Day 90 – User-Defined Functions

CREATE FUNCTION fnGetProductPrice (@ProductID INT)
RETURNS DECIMAL(18,2)
AS
BEGIN
    DECLARE @Price DECIMAL(18,2)
    SELECT @Price = Price * (1 - Discount) FROM Products WHERE ProductID = @ProductID
    RETURN @Price
END

SELECT ProductName, fnGetProductPrice(ProductID) AS DiscountedPrice
FROM Products

In this example, a user-defined function named fnGetProductPrice is created to retrieve the discounted price of a product based on the product ID. The function is then used in a query to retrieve the discounted price for each product.