Advertisement
Intermediate SQL Server, Dynamic SQL

How do you safely use sp_executesql to execute dynamic SQL with parameters, avoiding the risks of simple string concatenation?

Short answer

sp_executesql lets you define a parameterized dynamic SQL statement and pass in parameter values separately, similar to how a regular stored procedure works, which both protects against SQL injection and allows SQL Server to reuse cached execution plans for better performance…

Save SQL Server mock interview
Advertisement
AModel answer
sp_executesql lets you define a parameterized dynamic SQL statement and pass in parameter values separately, similar to how a regular stored procedure works, which both protects against SQL injection and allows SQL Server to reuse cached execution plans for better performance compared to plain string concatenation.
DECLARE @SQL NVARCHAR(MAX) = N'SELECT * FROM Orders WHERE CustomerId = @CustId';
EXEC sp_executesql @SQL, N'@CustId INT', @CustId = 123;
Real-world example
A reporting application safely filters orders by a customer id provided by the user, using sp_executesql with a proper parameter instead of concatenating the value directly into the SQL string, protecting against injection attacks.
Likely follow-ups
  • Why does using parameters also improve performance through plan reuse?
  • What data types can be used as parameters with sp_executesql?
Related topics