In SQL Server, what is the difference between running dynamic SQL with EXEC (@sql) and with sp_executesql, and why does it matter?
answer
- values inside the string or beside it
- identical text, reused plan
- a Unicode statement plus a definition string
- separate scope from the caller
- a 2025 option for compile storms
basics
~20 sEXEC (@sql) runs a string, so values must be concatenated in as literals. sp_executesql takes a Unicode statement plus typed parameters, so the text stays constant: its plan is reused and values cannot alter the statement's structure.
solid answer
~50 s`EXEC (@sql)` executes whatever string it is given, so every value has to be concatenated into the text. Each distinct value produces distinct text, which usually means a new ad hoc plan, and a value containing a quote can rewrite the statement. `sp_executesql` takes the statement as an `nvarchar` constant or variable, a definition string like `N'@id INT, @cnt INT OUTPUT'` and the values. The text never changes, so the optimizer reuses one plan, much like a stored procedure, and values are bound as typed data, never parsed as SQL. Both run in their own batch: they cannot see the caller's variables, and a `USE` inside lasts only until they finish. For a local dynamic batch, only `sp_executesql` can hand values back through `OUTPUT` parameters. Table and column names still need an allowlist and `QUOTENAME`. SQL Server 2025 adds `OPTIMIZED_SP_EXECUTESQL`, which makes concurrent identical batches wait for one compile.
code
sql · 11 linesDECLARE @sql NVARCHAR(MAX) =
N'SELECT @cnt = COUNT(*) FROM sys.objects WHERE type = @type;';
DECLARE @n INT;
EXEC sys.sp_executesql
@sql,
N'@type CHAR(2), @cnt INT OUTPUT',
@type = 'U',
@cnt = @n OUTPUT;
SELECT @n AS user_tables;go deeper
Recall that EXEC runs a finished string while sp_executesql takes a Unicode statement plus a parameter definition string and separate values.
Explain why constant text gives plan reuse and injection safety. Also cover the Unicode-only statement, the constant-or-variable rule for values, and the separate batch scope.
Bring the production angle: dynamic SQL inside procedures loses ownership chaining, identifiers need an allowlist plus QUOTENAME, and parallel compiles of identical batches can bloat the plan cache.
Decide where dynamic SQL is allowed at all, what permission model it runs under, and whether the SQL Server 2025 serialized-compile option belongs in your database baseline.
## Two ways to run a string in SQL Server **Dynamic SQL** is T-SQL built as a string at run time and then executed. SQL Server gives you two ways to execute such a string: - `EXEC (@sql)` (or `EXECUTE (@sql)`): executes a character string as a batch. - `sp_executesql`: a system stored procedure that executes a statement or batch which can contain **embedded parameters**, declared in a separate definition string and supplied as separate values. Both compile the string only when they run, as a plan separate from the calling batch. The difference lies in how values get into the statement. | Aspect | `EXEC (@sql)` | `sp_executesql` | |---|---|---| | How values arrive | Concatenated into the text as literals | Passed as typed parameters beside the text | | Statement text | Changes with every distinct value | Constant between calls | | Plan reuse | Usually one ad hoc plan per distinct string | One plan, reused like a stored procedure's | | Injection exposure | Any value can change the statement | Values are data and are never parsed as SQL | | Return values (local batch) | None besides result sets | `OUTPUT` parameters supported | | Statement type | Any character string | Must be Unicode: an `N'...'` constant or an `nvarchar` variable | ## Plan reuse: why constant text matters SQL Server caches compiled plans and matches a new statement against the cache by its text. With `EXEC`, a search for customer 42 and a search for customer 43 are two different strings, so each normally gets its own compile and its own cache entry. Simple parameterization, or forced parameterization where a database enables it, can turn some of these into one shared plan, but you cannot count on it. With `sp_executesql`, the text is `... WHERE CustomerId = @CustomerId` both times, and only the parameter value changes. The documentation puts it this way: the optimizer is likely to reuse the plan from the first execution, with performance equivalent to a stored procedure. Other benefits the documentation lists: - The string is built once. - An integer parameter is passed in its native type, with no conversion to text and back. ## The rules of sp_executesql 1. `@stmt` must be a **Unicode constant or Unicode variable**. A `varchar` variable, or an expression such as `N'...' + @x` written directly in the call, is rejected. Passing a non-Unicode string fails with error 214, which reports a parameter of the wrong type. Build the string in an `nvarchar(max)` variable first. 2. `@params` is a single Unicode string declaring every parameter the statement uses, with types and optional `OUTPUT`. 3. Each value in the value list must be a **constant or a variable**. A function call such as `GETDATE()` or an expression such as `@Price * 1.2` is not allowed there. Assign it to a variable first. 4. The arguments must come in the documented order: statement, definition string, values. ## Scope, permissions and identifiers Both forms run their string as a **separate batch**: - The dynamic batch cannot reference variables declared by the caller. Referring to one fails with Msg 137, "Must declare the scalar variable". - Local variables and cursors created inside are not visible to the caller afterwards. - A database context change inside (`USE`) lasts only until the dynamic batch ends. - Inside a procedure, **ownership chaining does not apply to dynamic queries**. The caller's own permissions are checked against the tables the string touches, unless the module uses `EXECUTE AS` or is signed. Parameters stand only for **values**. Neither form lets you bind a table name, column name or sort direction. Those must be chosen from an allowlist and wrapped with `QUOTENAME`, which delimits an identifier and escapes any closing bracket inside it. Why concatenating values is an injection hole in the first place belongs to the application-security material on injection. Here the point is which T-SQL call avoids it. ## OPTIMIZED_SP_EXECUTESQL in SQL Server 2025 By default, when many sessions submit the same `sp_executesql` batch at once, they can all compile it in parallel, and each puts its own plan into the cache. In some cases those copies replace or duplicate one another. SQL Server 2025 adds the `OPTIMIZED_SP_EXECUTESQL` database scoped configuration, **off by default**. When it is on, identical batches (ignoring parameter values) compile the way stored procedures do: the first session takes a compile lock and caches its plan, and the others wait for that plan and then reuse it. If automatic statistics update is enabled, the documentation says you should also enable asynchronous statistics update with the `ASYNC_STATS_UPDATE_WAIT_AT_LOW_PRIORITY` configuration before turning it on, to reduce long compiles and waits on exclusive locks. ## What to say in an interview - Default to `sp_executesql` with parameters for any dynamic statement that includes a value. - Keep `EXEC (@sql)` for strings that contain no external values, such as maintenance commands built from catalog names, and still use `QUOTENAME` on those names. - Remember that both forms run in a separate scope with the caller's permissions.
- In SQL Server, can sp_executesql return a value to the calling batch, and how?Yes. Declare the parameter with `OUTPUT` inside the definition string, for example `N'@cnt INT OUTPUT'`, assign it inside the statement, and pass a caller variable with `OUTPUT` in the value list: `@cnt = @n OUTPUT`. This is the standard way to get a scalar result out of dynamic SQL, because the dynamic batch cannot assign the caller's variables directly.
- Inside a SQL Server stored procedure, why might a user with EXECUTE permission get a permission error from its dynamic SQL?Ownership chaining, which normally lets a procedure read tables its owner also owns without checking the caller, does not apply to dynamic queries. The string's statements are checked against the caller's own permissions. The fixes are granting the needed permissions, adding `EXECUTE AS` to the procedure, or signing the module with a certificate. Each one widens what the dynamic code can do, which matters if it could be injected.
- When would you turn on OPTIMIZED_SP_EXECUTESQL in SQL Server 2025?When many sessions submit the same parameterized `sp_executesql` batch at once and compile it in parallel. That shows up as compile CPU spikes and duplicated plan cache entries. With the option on, the first session compiles under a compile lock, and the others wait and reuse its plan. It is off by default. If automatic statistics update is on, the documentation says to enable asynchronous statistics update with `ASYNC_STATS_UPDATE_WAIT_AT_LOW_PRIORITY` first.
EXEC (@sql) is like writing out a new letter for each customer: the text is different every time, and anything a customer dictates goes straight into it. sp_executesql is a printed form with labelled blanks. The form stays the same, so it is recognised at a glance, and nothing written in a blank can change the form's wording. The blanks only hold values, though. You cannot add a new field by writing in one, just as a parameter cannot name a column.
- EXEC and sp_executesql are interchangeable once the string is built
- sp_executesql accepts a varchar statement just as well as nvarchar
- Dynamic SQL can read the variables declared in the calling batch
- A table or column name can be passed as an sp_executesql parameter
- Wrapping a statement in sp_executesql makes it safe even when values are concatenated
- Ownership chaining covers dynamic SQL run inside a procedure
Assumes SQL Server 2025; the OPTIMIZED_SP_EXECUTESQL database scoped configuration is new in 2025 and off by default, while the rest applies to every supported release.