Modifying data safely
Previewing changes and rolling them back
Compare a value before, during, and after a rolled-back change.
Lesson 50 of 84
Reading: about 2 min
Lesson + practice: about 15 min
Difficulty: Intermediate
On this page4 sections
This lesson uses DDI_SQL_Training dataset v1.0.0 on SQL Server 2019 or later. Compare a value before, during, and after a rolled-back change. Run changing examples only on a disposable training instance. The example uses a session-local object or rolls back its changes.
Run the example
DECLARE @Before decimal(10,2) = (SELECT ListPrice FROM dbo.Products WHERE ProductID = 1);
BEGIN TRANSACTION;
UPDATE dbo.Products SET ListPrice = ListPrice + 5.00 WHERE ProductID = 1;
DECLARE @During decimal(10,2) = (SELECT ListPrice FROM dbo.Products WHERE ProductID = 1);
ROLLBACK TRANSACTION;
SELECT @Before AS BeforePrice, @During AS DuringPrice,
ListPrice AS AfterRollbackPrice
FROM dbo.Products WHERE ProductID = 1;Read it step by step
- DECLARE @Before decimal(10,2) creates a variable: a named, typed value that lasts until the end of the batch. Variable names start with @. Here it saves the starting price.
- Change the single row inside a transaction and capture its temporary value in a second variable, @During.
- ROLLBACK restores the row; the final SELECT compares before, during, and after.
Check the result
| BeforePrice | DuringPrice | AfterRollbackPrice |
|---|---|---|
| 39.00 | 44.00 | 39.00 |
BeforePrice and AfterRollbackPrice match in the unmodified dataset.
Practice
Repeat for ProductID 2 with a temporary increase of 10.00.
Check your answer and expected result
Reveal answer
DECLARE @Before decimal(10,2) = (SELECT ListPrice FROM dbo.Products WHERE ProductID = 2);
BEGIN TRANSACTION;
UPDATE dbo.Products SET ListPrice = ListPrice + 10.00 WHERE ProductID = 2;
DECLARE @During decimal(10,2) = (SELECT ListPrice FROM dbo.Products WHERE ProductID = 2);
ROLLBACK TRANSACTION;
SELECT @Before AS BeforePrice, @During AS DuringPrice,
ListPrice AS AfterRollbackPrice
FROM dbo.Products WHERE ProductID = 2;| BeforePrice | DuringPrice | AfterRollbackPrice |
|---|---|---|
| 129.00 | 139.00 | 129.00 |
The during price is ten higher; after rollback the original price returns.
Your progress
Reveal the check answer or reach the end to complete this lesson.