|
| 1 | +-- ******************************************************** -- |
| 2 | +-- Scalar UDF Inlining |
| 3 | + |
| 4 | +-- See https://aka.ms/IQP for more background |
| 5 | + |
| 6 | +-- Demo scripts: https://aka.ms/IQPDemos |
| 7 | + |
| 8 | +-- Demo uses SQL Server 2019 Public Preview and also works on Azure SQL DB |
| 9 | + |
| 10 | +-- Email IntelligentQP@microsoft.com for questions\feedback |
| 11 | +-- ******************************************************** -- |
| 12 | +USE WideWorldImportersDW; |
| 13 | +GO |
| 14 | + |
| 15 | +ALTER DATABASE WideWorldImportersDW |
| 16 | +SET COMPATIBILITY_LEVEL = 150; |
| 17 | +GO |
| 18 | + |
| 19 | +ALTER DATABASE SCOPED CONFIGURATION |
| 20 | +CLEAR PROCEDURE_CACHE; |
| 21 | +GO |
| 22 | +/* |
| 23 | +Adapted from SQL Server Books Online |
| 24 | +https://docs.microsoft.com/en-us/sql/relational-databases/user-defined-functions/scalar-udf-inlining?view=sqlallproducts-allversions |
| 25 | +*/ |
| 26 | +CREATE OR ALTER FUNCTION |
| 27 | + dbo.customer_category(@CustomerKey INT) |
| 28 | +RETURNS CHAR(10) AS |
| 29 | +BEGIN |
| 30 | + DECLARE @total_amount DECIMAL(18,2); |
| 31 | + DECLARE @category CHAR(10); |
| 32 | + |
| 33 | + SELECT @total_amount = |
| 34 | + SUM([Total Including Tax]) |
| 35 | + FROM [Fact].[OrderHistory] |
| 36 | + WHERE [Customer Key] = @CustomerKey; |
| 37 | + |
| 38 | + IF @total_amount < 500000 |
| 39 | + SET @category = 'REGULAR'; |
| 40 | + ELSE IF @total_amount < 1000000 |
| 41 | + SET @category = 'GOLD'; |
| 42 | + ELSE |
| 43 | + SET @category = 'PLATINUM'; |
| 44 | + |
| 45 | + RETURN @category; |
| 46 | +END |
| 47 | +GO |
| 48 | + |
| 49 | +-- Before (show actual query execution plan for legacy behavior) |
| 50 | +SELECT TOP 100 |
| 51 | + [Customer Key], [Customer], |
| 52 | + dbo.customer_category([Customer Key]) AS [Discount Price] |
| 53 | +FROM [Dimension].[Customer] |
| 54 | +ORDER BY [Customer Key] |
| 55 | +OPTION (RECOMPILE,USE HINT('DISABLE_TSQL_SCALAR_UDF_INLINING')); |
| 56 | + |
| 57 | +-- After (show actual query execution plan for Scalar UDF Inlining) |
| 58 | +SELECT TOP 100 |
| 59 | + [Customer Key], [Customer], |
| 60 | + dbo.customer_category([Customer Key]) AS [Discount Price] |
| 61 | +FROM [Dimension].[Customer] |
| 62 | +ORDER BY [Customer Key] |
| 63 | +OPTION (RECOMPILE); |
| 64 | + |
| 65 | + |
0 commit comments