User Defined Inline Table-Valued Functions with CROSS APPLY | Microsoft Fabric Tutorial
In this Microsoft Fabric tutorial, we’ll demonstrate how to create and use inline table-valued functions (iTVFs)
and apply them with CROSS APPLY
. These are great tools for reusable logic and dynamic row-by-row evaluation.
๐ง What is a Function in SQL?
A function is a reusable SQL object that returns either a value or a table. In Fabric Warehouse, only inline table-valued functions (iTVFs) are currently supported.
๐ซ Not Supported:
- Scalar functions
- Multi-statement table-valued functions
✅ Supported:
- Inline Table-Valued Functions (iTVFs)
๐️ Step 1: Create Sample Orders Table
CREATE TABLE dbo.Orders (
OrderID INT,
CustomerName VARCHAR(100),
OrderDate DATE,
OrderAmount DECIMAL(10, 2)
);
๐พ Step 2: Insert Sample Data
INSERT INTO dbo.Orders VALUES
(1, 'Aamir', '2024-01-10', 1200.00),
(2, 'Sara', '2024-02-15', 800.00),
(3, 'John', '2024-03-20', 300.00),
(4, 'Mia', '2024-03-22', 1500.00),
(5, 'Aamir', '2024-04-01', 200.00);
๐ Step 3: Create Discount Function with CROSS APPLY
This iTVF applies a 10% discount to a given amount:
CREATE FUNCTION dbo.fn_ApplyDiscount (@Amount DECIMAL(10,2))
RETURNS TABLE
AS
RETURN (
SELECT @Amount * 0.90 AS DiscountedAmount
);
✅ Using CROSS APPLY
SELECT
o.OrderID, o.CustomerName, o.OrderAmount,
d.DiscountedAmount
FROM dbo.Orders o
CROSS APPLY dbo.fn_ApplyDiscount(o.OrderAmount) d;
๐ธ Step 4: Create Function to Filter Orders
This function returns orders where the amount is greater than or equal to a specified value:
CREATE FUNCTION dbo.fn_GetHighValueOrders (@MinAmount DECIMAL(10,2))
RETURNS TABLE
AS
RETURN (
SELECT OrderID, CustomerName, OrderAmount
FROM dbo.Orders
WHERE OrderAmount >= @MinAmount
);
✅ Usage Example:
SELECT * FROM dbo.fn_GetHighValueOrders(200.00);
๐งน Optional Cleanup
-- DROP FUNCTION dbo.fn_ApplyDiscount;
-- DROP FUNCTION dbo.fn_GetHighValueOrders;
-- DROP TABLE dbo.Orders;