SQL Flow Field Guide

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

  1. Read the statement text and identify the @MinimumPoints placeholder.
  2. Match the placeholder to the type declaration in @Parameters.
  3. Trace the final named argument to the local integer variable.
  4. Observe that the query reads only inline synthetic values and does not concatenate user input into its SQL text.
  5. 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 Flow
DECLARE @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