sp_executesql
parameterized dynamic SQL in a child batch scope
What changes
- Input
- statement string, parameter definition string, parameter values
- Output or change
- results, OUTPUT parameters, side effects of the inner statement
Syntax at a glance
sp_executesql [ @stmt = ] N'statement'
[
[ , [ @params = ] N'@parameter_name data_type [ { OUT | OUTPUT } ] [ , ...n ]' ]
[ , [ @param1 = ] 'value1' [ , ...n ] ]
]
Work example
A report needs dynamic filters whose values change while the statement shape stays fixed.
Review parameter declarations and bind each value separately instead of joining user input into SQL text.
Check your work Returns line_total 37.50. This call executes only the parameterized SELECT text.
Practice SQL
Open in SQL FlowOpen the SQL for a walkthrough. Run the example in SQL Server to check its result.
EXEC sys.sp_executesql @stmt = N'SELECT @price * @quantity AS line_total', @params = N'@price decimal(10,2), @quantity int', @price = 12.50, @quantity = 3;
Open Microsoft Learn for full syntax, permissions, and details for your version.