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.
On this page · 5 min · Intermediate
On this page
- Learning objectives
- Explanation
- Step-by-step screens
- Code example
- Step by step
- Real-world use
- Common mistakes
- Best practices
- Remember this
- Practice exercise
- Mini quiz
- Related topics
- My notes
- Reading time
- 5 min
- Difficulty
- Intermediate
- Updated
- Nov 26, 2026
Related tutorials
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#
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';
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#
- @SortBy is checked against an allow-list.
- Only the filters the caller supplied are added.
- Values stay as parameters @Name and @MaxPrice inside the string.
- QUOTENAME wraps the sort column.
- 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#
'… WHERE Name = ''' + @Name + '''' lets input like x' OR 1=1 -- change the query.
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
EXEC sp_executesql N'SELECT * FROM dbo.Products WHERE Price > @p', N'@p DECIMAL(10,2)', @p = 1000;
Mini quiz#
How do you safely use a user-chosen sort column?
Want more? Practise all SQL Server MCQs · SQL Server interview questions
My notes#
Saved in this browser.