Bind values in dynamic SQL
Keep SQL text separate from user supplied values when a query must be executed dynamically.
What you are trying to do
A report builds a fixed query string and supplies the points threshold through sp_executesql. The user value is data, not part of the SQL text.
Work through it
- Read the statement text and identify the @MinimumPoints placeholder.
- Match the placeholder to the type declaration in @Parameters.
- Trace the final named argument to the local integer variable.
- Observe that the query reads only inline synthetic values and does not concatenate user input into its SQL text.
- In application code, pass user values through parameters. Allow-list any dynamic object names because identifiers cannot be bound as values.
Check your work
The dynamic query returns task 101 with 8 points and task 103 with 12 points. The threshold value 7 appears only as a bound integer parameter. The query string contains a placeholder, not the value concatenated into SQL.
Practice SQL
Open in SQL FlowDECLARE @MinimumPoints int = 7;
DECLARE @Statement nvarchar(max) = N'SELECT TaskId, Title, Points FROM (VALUES (101, N''Cache review'', 8), (102, N''Queue alert'', 4), (103, N''Usage report'', 12)) AS WorkItem(TaskId, Title, Points) WHERE Points >= @MinimumPoints ORDER BY TaskId;';
DECLARE @Parameters nvarchar(100) = N'@MinimumPoints int';
EXEC sys.sp_executesql @stmt = @Statement, @params = @Parameters, @MinimumPoints = @MinimumPoints;
Knowledge check
Commands in this lesson
Next lesson Read a view as a named query