T-SQL: Dynamic SQL and SQL Injection (sp_executesql)


When we create dynamic SQL code, we can add the parameters in two ways:

  1. Concatenate them into the dynamic code with +
  2. Use sp_executesql

In this example I will show both scenarios when a SQL injection is involved.

First Name

Concatenate the parameters into the dynamic code with +

Concatenate

Concatenate Print

Concatenate and SQL injection.

Concatenate SQL Injection

Concatenate SQL Injection Print

Plug the parameters into the dynamic code with sp_executesql

sp_executesql

sp_executesql Print

sp_executesql and SQL Injection

sp_executesql SQL Injection

sp_executesql SQL Injection Print

As shown in the example above, it is recommended to execute dynamic SQL only with sp_executesql.

Keep it simple :-)

Leave a comment

Your email address will not be published. Required fields are marked *