Advanced T-SQL and application patterns
Stored procedures and parameters
Call a parameterized procedure created only inside a rolled-back teaching transaction.
Lesson 78 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 parameterized procedure created only inside 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 PROCEDURE dbo.DDI_LessonProductByID @ID int AS
SELECT ProductID, ProductName FROM dbo.Products WHERE ProductID = @ID');
EXEC dbo.DDI_LessonProductByID @ID = 1;
ROLLBACK TRANSACTION;Read it step by step
- The procedure declares a typed @ID parameter.
- EXEC creates it in a separate dynamic batch because CREATE PROCEDURE must start its batch.
- The next EXEC passes 1; ROLLBACK removes the disposable dbo procedure created in this transaction.
Check the result
| ProductID | ProductName |
|---|---|
| 1 | Laptop Stand |
A stored procedure saves executable statements, not the product row itself.
Practice
Create a rolled-back procedure that returns ProductID 2 from a typed parameter.
Check your answer and expected result
Reveal answer
BEGIN TRANSACTION;
EXEC(N'CREATE PROCEDURE dbo.DDI_LessonProductByID2 @ID int AS
SELECT ProductID, ProductName FROM dbo.Products WHERE ProductID = @ID');
EXEC dbo.DDI_LessonProductByID2 @ID = 2;
ROLLBACK TRANSACTION;| ProductID | ProductName |
|---|---|
| 2 | USB-C Dock |
The procedure returns product 2 and leaves no procedure behind after rollback.
Your progress
Reveal the check answer or reach the end to complete this lesson.