Search code examples
c#sql-injection

C# prevent SQL injection for create statement


Does it make sense to prevent sql injection for a create statement? How could I do this? I wanted to use command parameters, but it doesn't seam to work:

Example:

var createSql = "CREATE TABLE @TableName (@Column1 ...)";
var command = new SqlCommand();

command.CommandText = createSql;
command.Parameters.AddWithValue("@TableName", "XYZ");
command.Parameters.AddWithValue("@Column1", "Col");

// somewhere else
command.Connection = connection;
command.ExecuteNonReader(); // --> exception: invalid syntax at @TableName

Edit: The Column and TableNames are generated depending on other data. Indirectly also on userinput, yes. The given create statement is incomplete. It is just an example.

My problem is, that it seems that the command parameters are not replaced.


Solution

  • You cannot use bind variables for table or column names.

    So you'll have to construct that SQL statement using string concatenation and if necessary, manual quoting/escaping, and be very careful how you go about it.

    Direct user input would be very dangerous, but if it is only indirectly, for example just choosing options for auto-generated names, you should be okay.