Advanced T-SQL and application patterns
User-defined functions
Call a scalar function created within a rolled-back teaching transaction.
Lesson 79 of 84
Reading: about 2 min
Lesson + practice: about 20 min
Difficulty: Advanced
On this page4 sections
This lesson uses DDI_SQL_Training dataset v1.0.0 on SQL Server 2019 or later. Call a scalar function created within a rolled-back teaching transaction. Run changing examples only on a disposable training instance. The example uses a session-local object or rolls back its changes.
Run the example
BEGIN TRANSACTION;
EXEC(N'CREATE FUNCTION dbo.DDI_LessonAddTax(@Price decimal(10,2))
RETURNS decimal(10,2) AS BEGIN RETURN @Price * 1.10; END');
SELECT ProductID, dbo.DDI_LessonAddTax(ListPrice) AS PriceWithTax
FROM dbo.Products WHERE ProductID BETWEEN 1 AND 2 ORDER BY ProductID;
ROLLBACK TRANSACTION;Read it step by step
- The scalar function receives a decimal price and returns a decimal value.
- The query invokes it for two products; it does not modify ListPrice.
- ROLLBACK removes the practice function. Inline expressions or inline table-valued functions can be preferable for performance.
Check the result
| ProductID | PriceWithTax |
|---|---|
| 1 | 42.90 |
| 2 | 141.90 |
The declared decimal(10,2) return type determines the displayed two-decimal result.
Practice
Create a rolled-back function that doubles a product price and call it for ProductID 1.
Check your answer and expected result
Reveal answer
BEGIN TRANSACTION;
EXEC(N'CREATE FUNCTION dbo.DDI_LessonDouble(@Price decimal(10,2))
RETURNS decimal(10,2) AS BEGIN RETURN @Price * 2; END');
SELECT ProductID, dbo.DDI_LessonDouble(ListPrice) AS DoubledPrice
FROM dbo.Products WHERE ProductID = 1;
ROLLBACK TRANSACTION;| ProductID | DoubledPrice |
|---|---|
| 1 | 78.00 |
The function returns a calculated value and leaves the product table unchanged.
Your progress
Reveal the check answer or reach the end to complete this lesson.