Advanced T-SQL and application patterns
Safe dynamic SQL and injection prevention
Pass values as parameters to dynamic SQL rather than concatenating them.
Lesson 81 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. Pass values as parameters to dynamic SQL rather than concatenating them.
Run the example
sql
DECLARE @Minimum decimal(10,2) = 100.00;
DECLARE @Sql nvarchar(max) = N'SELECT ProductID, ListPrice
FROM dbo.Products WHERE ListPrice > @Limit ORDER BY ProductID';
EXEC sys.sp_executesql @Sql, N'@Limit decimal(10,2)', @Limit = @Minimum;Read it step by step
- @Sql contains the fixed query shape and an @Limit placeholder.
- sp_executesql binds a typed decimal value separately from SQL syntax.
- The result includes prices above 100 and is ordered by ProductID.
Check the result
| ProductID | ListPrice |
|---|---|
| 2 | 129.00 |
| 9 | 119.00 |
| 13 | 189.00 |
| 15 | 149.00 |
No user-provided text is concatenated into the query.
Practice
Run the same parameterized query with a minimum price of 150.
Check your answer and expected result
Reveal answer
sql
DECLARE @Minimum decimal(10,2) = 150.00;
DECLARE @Sql nvarchar(max) = N'SELECT ProductID, ListPrice
FROM dbo.Products WHERE ListPrice > @Limit ORDER BY ProductID';
EXEC sys.sp_executesql @Sql, N'@Limit decimal(10,2)', @Limit = @Minimum;| ProductID | ListPrice |
|---|---|
| 13 | 189.00 |
Only prices above 150 appear; the input remains data, not executable SQL.
Your progress
Reveal the check answer or reach the end to complete this lesson.