SQL Server › Dynamic SQL
How do you safely use sp_executesql to execute dynamic SQL with parameters, avoiding the risks of simple string concatenation?
IntermediateAnswer
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.