SQL Server · Advanced Querying

Dynamic SQL

Sometimes the SQL itself must change — optional filters, a user-chosen sort column, column lists. Dynamic SQL does it, and parameters keep it safe.

Intermediate 5 min Lesson 34 of 44Examples run on SQL Server 2022 and Azure SQL Database.
0/44 in SQL Server
On this page · 5 min · Intermediate

Learning objectives#

  • Run dynamic SQL with sp_executesql
  • Pass values as parameters, never concatenated
  • Protect object names with QUOTENAME and allow-lists
  • Build optional-filter searches

Explanation#

sp_executesql runs a string of SQL. The second argument declares parameters and the rest pass their values. Values passed this way can never change the SQL, which prevents SQL injection and lets SQL Server reuse the plan.

Object names (tables, columns, sort order) cannot be parameters. Check them against an allow-list and wrap them with QUOTENAME().

A classic use is a search screen with many optional filters: add only the WHERE conditions the user filled in, so each combination gets its own efficient plan.

Avoid EXEC(@sql) with values glued into the string — that is how injection happens.

Step-by-step screens#

Drawings of SQL Server 2022 Setup and SQL Server Management Studio (SSMS 20) with the ShopDB sample database. The red numbers match the numbered actions under each picture; names on your computer will differ.

Loading pictures…

Code example: Product search with optional filters#

SQLProduct search with optional filters Illustrative
CREATE OR ALTER PROCEDURE dbo.SearchProducts
    @Name NVARCHAR(100) = NULL, @MaxPrice DECIMAL(10,2) = NULL, @SortBy SYSNAME = N'Name'
AS
BEGIN
    IF @SortBy NOT IN (N'Name', N'Price') SET @SortBy = N'Name';     -- allow-list


    DECLARE @sql NVARCHAR(MAX) = N'SELECT ProductId, Name, Price FROM dbo.Products WHERE 1 = 1';
    IF @Name IS NOT NULL     SET @sql += N' AND Name LIKE @Name + N''%''';
    IF @MaxPrice IS NOT NULL SET @sql += N' AND Price <= @MaxPrice';
    SET @sql += N' ORDER BY ' + QUOTENAME(@SortBy) + N';';


    EXEC sp_executesql @sql,
         N'@Name NVARCHAR(100), @MaxPrice DECIMAL(10,2)',
         @Name = @Name, @MaxPrice = @MaxPrice;
END;
GO
EXEC dbo.SearchProducts @Name = N'Key', @MaxPrice = 2000, @SortBy = N'Price';
Expected output
ProductId  Name                Price
---------  ------------------  -------
14         Keyboard Basic      699.00
3          Keyboard Wireless   1399.00

This example is illustrative. Copy or download it and run it in your own environment; the expected output is shown above.

Step-by-step explanation#

  1. @SortBy is checked against an allow-list.
  2. Only the filters the caller supplied are added.
  3. Values stay as parameters @Name and @MaxPrice inside the string.
  4. QUOTENAME wraps the sort column.
  5. sp_executesql declares and passes the parameters.

Real-world use case#

An admin product search with eight optional filters stays fast because each filter combination gets its own small plan, instead of one catch-all plan with OR conditions.

Common mistakes#

Concatenating user input

'… WHERE Name = ''' + @Name + '''' lets input like x' OR 1=1 -- change the query.

Parameterising a column name

ORDER BY @SortBy sorts by a constant. Use an allow-list and QUOTENAME.

Best practices#

  • Always sp_executesql with parameters
  • Allow-list object names
  • QUOTENAME every identifier
  • PRINT @sql while developing

Remember this#

Values → parameters.

Names → allow-list + QUOTENAME.

Never EXEC(@sql) with user input.

Practice exercise#

Your task: Run SELECT * FROM dbo.Products WHERE Price > @p with @p = 1000 using sp_executesql.

Show solution
SQL Illustrative
EXEC sp_executesql N'SELECT * FROM dbo.Products WHERE Price > @p', N'@p DECIMAL(10,2)', @p = 1000;

Mini quiz#

Dynamic SQL quizMultiple choice Question 1 of 1

How do you safely use a user-chosen sort column?

Score so far: 0/0

Want more? Practise all SQL Server MCQs · SQL Server interview questions

My notes#

Saved in this browser.

Progress is saved in this browser. Sign in to sync.