Recipe 2.5 · Python
Optional-Parameter Search with sp_executesql
This recipe has no Python listing. The explanation and any SQL below apply to both languages; switch to C# for the .NET code.
Problem
A search screen has six optional filters. Either the procedure uses one static query full of @Param IS NULL OR conditions, which gets a single plan that is bad for most combinations, or it builds SQL with string concatenation and runs it with EXEC, which is an injection hole. In my archive, EXEC(@variable) appears in about 788 files across 23 engagements, close behind the 1,148 files that use the parameterized sp_executesql.
The way it's often written
Anti-pattern: shown so you can recognize it. Don't copy this one.
-- Not to copy: injection through EXEC.
DECLARE @sql varchar(4000)
SET @sql = 'SELECT * FROM Customer WHERE 1 = 1'
IF @Name IS NOT NULL
SET @sql = @sql + ' AND Name LIKE ''' + @Name + '%'''
IF @City IS NOT NULL
SET @sql = @sql + ' AND City = ''' + @City + ''''
SET @sql = @sql + ' ORDER BY ' + @SortColumn
EXEC (@sql)
@Name, @City and @SortColumn all go straight into the SQL text. A name containing a quote breaks the query, and a crafted one runs anything the caller's login can run. Every distinct value also compiles a new plan.
The improved recipe
CREATE OR ALTER PROCEDURE dbo.Customer_Search
@Name NVARCHAR(100) = NULL,
@City NVARCHAR(60) = NULL,
@CreatedFrom DATE = NULL,
@SortBy VARCHAR(20) = 'Name',
@MaxRows INT = 200
AS
BEGIN
SET NOCOUNT ON;
DECLARE @sql NVARCHAR(MAX) = N'
SELECT TOP (@MaxRows)
c.CustomerId, c.Name, c.City, c.CreatedUtc
FROM dbo.Customer AS c
WHERE c.IsActive = 1';
IF @Name IS NOT NULL
SET @sql += N'
AND c.Name LIKE @Name + N''%''';
IF @City IS NOT NULL
SET @sql += N'
AND c.City = @City';
IF @CreatedFrom IS NOT NULL
SET @sql += N'
AND c.CreatedUtc >= @CreatedFrom';
SET @sql += N'
ORDER BY ' + CASE @SortBy
WHEN 'City' THEN N'c.City, c.Name, c.CustomerId'
WHEN 'Created' THEN N'c.CreatedUtc DESC, c.CustomerId'
ELSE N'c.Name, c.CustomerId'
END + N';';
DECLARE @params NVARCHAR(400) =
N'@Name NVARCHAR(100), @City NVARCHAR(60), '
+ N'@CreatedFrom DATE, @MaxRows INT';
EXEC sys.sp_executesql
@sql,
@params,
@Name = @Name,
@City = @City,
@CreatedFrom = @CreatedFrom,
@MaxRows = @MaxRows;
END;
How it works
The procedure builds the SQL text from fixed fragments only. Each optional filter adds a condition that refers to a parameter by name, never to the parameter's value. The sort order comes from a CASE expression that maps the caller's choice to a known ORDER BY list, so @SortBy can never inject anything: an unknown value falls through to the default.
sp_executesql runs the text with real, typed parameters. SQL Server caches one plan per distinct text, which means one plan per combination of filters. A search by city gets a plan built for a city search, and a search by name gets a plan built for a name search, with an index seek on Name for the prefix LIKE.
Every parameter is declared in @params and passed every time, even when the text does not use it. sp_executesql ignores parameters the text does not reference, and declaring them all keeps the call simple.
Variations and pitfalls
OPTION (RECOMPILE)alternative. A static query with(@City IS NULL OR c.City = @City)conditions plusOPTION (RECOMPILE)gets a fresh plan on every call, built for the actual values. It is simpler to read and fine for searches that run a few times a minute. For searches that run hundreds of times a second, the compile cost adds up and the dynamic version wins.- Permissions. Dynamic SQL runs with the permissions of the caller, not the procedure owner, so ownership chaining no longer applies. A user with only
EXECUTEon the procedure will get a permission error ondbo.Customer. GrantSELECT, or sign the procedure with a certificate. - Identifiers. If you truly must put a table or column name into dynamic SQL, validate it against
sys.columnsor a whitelist and wrap it withQUOTENAME(). Never concatenate a raw value. - Debugging. Add a
@Debug BIT = 0parameter andPRINT @sqlwhen it is set. You will want to see the generated text. - Keep fragments on their own lines as shown. The generated SQL is readable when printed, and a missing space between fragments cannot glue two keywords together.