skip to content

A SQL Server search procedure concatenates optional filter values and a sort column into a string run with EXEC; how do you rewrite it safely without wrecking plan reuse?

level: seniorimportance: should knowfreq 52%

answer

  1. values in parameters, never in text
  2. append only the filters supplied
  3. identifiers come from a list
  4. QUOTENAME and its 128 limit
  5. the caller's permissions apply

basics

~20 s

Build only the predicates that were supplied, each referencing a parameter, and run the string with sp_executesql passing every value as a typed parameter. Pick the sort column from an allowlist and wrap it in QUOTENAME.

solid answer

~50 s

The concatenated version has three problems: any value can change the statement, every distinct value means new text and a new ad hoc plan, and the sort name is injectable too. The rewrite appends a fixed fragment like `AND CustomerId = @CustomerId` only when that filter is non-NULL. The values never enter the string. I run it with `sp_executesql`, declaring all the optional parameters in the definition string every time. That gives one cached plan per combination of filters actually used, not one per value. The sort column can't be a parameter, so I map an input code to a known column name with `CASE`, fall back to a default, and wrap it in `QUOTENAME`. Dynamic SQL loses ownership chaining, so callers need `SELECT` on the table unless the procedure uses `EXECUTE AS` or is signed. For a rarely called search, a static catch-all with `OPTION (RECOMPILE)` is simpler.

code

sql · 41 lines
sql
CREATE TABLE dbo.Orders (
    OrderId    INT IDENTITY PRIMARY KEY,
    CustomerId INT NOT NULL,
    Amount     DECIMAL(12, 2) NOT NULL,
    OrderDate  DATE NOT NULL
);
GO
CREATE OR ALTER PROCEDURE dbo.usp_SearchOrders
    @CustomerId INT = NULL,
    @MinAmount  DECIMAL(12, 2) = NULL,
    @FromDate   DATE = NULL,
    @SortBy     VARCHAR(20) = 'date'
AS
BEGIN
    SET NOCOUNT ON;

    DECLARE @sortColumn SYSNAME =
        CASE @SortBy
            WHEN 'date'   THEN N'OrderDate'
            WHEN 'amount' THEN N'Amount'
            WHEN 'id'     THEN N'OrderId'
        END;
    IF @sortColumn IS NULL
        SET @sortColumn = N'OrderDate';

    DECLARE @sql NVARCHAR(MAX) =
        N'SELECT OrderId, CustomerId, Amount, OrderDate FROM dbo.Orders WHERE 1 = 1';
    IF @CustomerId IS NOT NULL SET @sql += N' AND CustomerId = @CustomerId';
    IF @MinAmount  IS NOT NULL SET @sql += N' AND Amount >= @MinAmount';
    IF @FromDate   IS NOT NULL SET @sql += N' AND OrderDate >= @FromDate';
    SET @sql += N' ORDER BY ' + QUOTENAME(@sortColumn) + N';';

    EXEC sys.sp_executesql
        @sql,
        N'@CustomerId INT, @MinAmount DECIMAL(12, 2), @FromDate DATE',
        @CustomerId = @CustomerId,
        @MinAmount  = @MinAmount,
        @FromDate   = @FromDate;
END;
GO
EXEC dbo.usp_SearchOrders @CustomerId = 42, @SortBy = 'amount';

go deeper

for a junior

Recall that filter values belong in sp_executesql parameters, never concatenated into the statement text, and that column names cannot be parameters.

for a middle

Explain how conditional fragments plus a fixed parameter list give one plan per filter combination, and why identifiers need an allowlist and QUOTENAME.

for a senior

Own the whole fix: injection, plan reuse and the permission model, including what EXECUTE AS adds. Choose dynamic SQL or a static OPTION (RECOMPILE) catch-all by call rate.

for a principal

Standardize one reviewed pattern for optional-filter searches, and decide which permission model dynamic SQL may use across your databases.

## The procedure as found A typical inherited search procedure takes optional filters (customer, minimum amount, start date) and a sort column. It glues them into a string and runs it: ```sql SET @sql = N'SELECT ... FROM dbo.Orders WHERE 1 = 1'; IF @CustomerId IS NOT NULL SET @sql += N' AND CustomerId = ' + CAST(@CustomerId AS NVARCHAR(12)); SET @sql += N' ORDER BY ' + @SortBy; EXEC (@sql); ``` It works, but it has three separate defects: - **Injection.** Any string-typed value, and the sort name in particular, becomes part of the statement text. A value can close the statement and add its own. - **Plan cache churn.** Each distinct customer number or date produces different text, so SQL Server usually compiles and caches a new ad hoc plan per value. Simple parameterization rescues only some simple statements. - **Hidden permission needs.** Inside a procedure, **ownership chaining does not apply to dynamic queries**. The caller needs direct permissions on `dbo.Orders`, not just `EXECUTE` on the procedure. ## Rewrite: parameterized dynamic SQL The fix keeps the dynamic shape, because a single static statement cannot use the best index for every filter combination. What changes is that values never enter the string: 1. **Append fixed fragments only.** For each supplied filter, append text such as `N' AND CustomerId = @CustomerId'`. The fragment names a parameter. It never contains the value. 2. **Declare every optional parameter every time.** Pass the same definition string, `N'@CustomerId INT, @MinAmount DECIMAL(12, 2), @FromDate DATE'`, and all the values on every call. A parameter declared but not used in a given shape is harmless. 3. **Execute with `sp_executesql`.** The statement must be an `nvarchar` value. Build it in an `nvarchar(max)` variable. The result is **one cached plan per filter combination** rather than one per value. A search by customer reuses the customer-shaped plan for every customer. A search by date range gets its own plan. Within each shape, plans are compiled for the first values seen. If one shape has very skewed data, the sniffing fixes from the performance lesson apply, such as `OPTION (RECOMPILE)` on that shape only. ## Identifiers: allowlist, then QUOTENAME Parameters stand only for values. A column name, table name or sort direction **cannot be a parameter** in `CREATE PROCEDURE` or in `sp_executesql`. So: - Accept a **code** (`'date'`, `'amount'`), not a column name, and map it to a known column with `CASE`. Unknown codes fall back to a default. - Wrap the chosen name in **`QUOTENAME`**, which adds brackets and doubles any `]` inside. `QUOTENAME` takes a `sysname`, and **input longer than 128 characters returns NULL**, which, with the default `CONCAT_NULL_YIELDS_NULL` setting, nulls the whole concatenated string. The allowlist means this can never happen to user input. - Choose sort direction the same way, from two literal strings. `QUOTENAME` alone is a second line of defence. The allowlist is what guarantees the sort can only ever name a column you intended. ## Permissions Because the dynamic statement is checked against the caller, choose a model on purpose: - **Grant `SELECT`** on the tables to the calling role. This is the simplest, but it exposes the tables directly. - **`EXECUTE AS`** on the procedure. The dynamic SQL runs with the named user's permissions, and the caller needs only `EXECUTE`. Combine it only with fully parameterized SQL, since any remaining injection would run with those rights. - **Module signing**: sign the procedure with a certificate and grant the extra permission to a user created from that certificate. ## The static alternative When the search is called rarely, a static statement can be simpler: ```sql WHERE (@CustomerId IS NULL OR CustomerId = @CustomerId) AND (@FromDate IS NULL OR OrderDate >= @FromDate) OPTION (RECOMPILE); ``` Without the hint, one cached plan must serve every combination, and it often serves many of them badly. With `OPTION (RECOMPILE)` the statement is compiled each execution using the values actually supplied, so the plan can fit the filters in use. The price is a compile on every call. | Approach | Plans | Compile cost | Fits | |---|---|---|---| | Concatenated `EXEC` | One per distinct value | High, plus cache bloat | Nothing: replace it | | `sp_executesql`, conditional fragments | One per filter combination | Low after warm-up | Frequent searches | | Static catch-all with `OPTION (RECOMPILE)` | Temporary, per execution | One compile per call | Infrequent searches | Either rewrite closes the injection hole. Choose between them by call rate.

  • Why does the rewrite declare all optional parameters in sp_executesql even when only one filter is used?
    The definition string and value list stay the same on every call, which keeps the code simple. A parameter declared but not referenced by the statement is allowed. Only parameters the statement does reference must be declared. Plan reuse is still decided by the full statement text, so each filter combination gets its own plan, reused across all values.
  • In SQL Server, what are the options when callers have EXECUTE on the search procedure but no SELECT on the table?
    Ownership chaining doesn't cover the dynamic statement, so it fails on permissions. You can grant `SELECT` to the calling role, add `EXECUTE AS` to the procedure so the dynamic SQL runs as a chosen user, or sign the procedure with a certificate whose user holds the permission. The last two keep the table hidden, but they make full parameterization essential, because any injection would run with the elevated rights.

  • Switching EXEC to sp_executesql is enough even if values stay concatenated
  • A column name can be passed as a parameter to sp_executesql
  • QUOTENAME alone ensures the sort can only name an intended column
  • Ownership chaining lets callers with only EXECUTE run the dynamic query
  • A catch-all WHERE with IS NULL OR checks gets a good plan for every filter combination without RECOMPILE