Search code examples
c#sqlodbcparameterized-query

Parameterize ALTER/DROP TABLE OdbcCommand in C#


I am trying to convert the SQL statements in my code from concatenated strings to parameterized queries, but I can not make it work for DROP TABLE and ALTER TABLE like these:

using (OdbcCommand delCmd = new OdbcCommand($"DROP TABLE IF EXISTS ?", dbConnection))
{
    delCmd.Parameters.Add(new OdbcParameter("?", OdbcType.NVarChar) { Value = tableName });
    delCmd.ExecuteNonQuery();
}


using (OdbcCommand delCmd = new OdbcCommand($"ALTER TABLE ? DROP COLUMN ?", dbConnection))
{
    delCmd.Parameters.Add(new OdbcParameter("?", OdbcType.NVarChar) { Value = tableName });
    delCmd.Parameters.Add(new OdbcParameter("?", OdbcType.NVarChar) { Value = columnName });
    delCmd.ExecuteNonQuery();
}

I have tried adding [] or '' to either the query string or the parameter, but I never got it to work.

I get run time error:

ERROR [42000] [Microsoft][ODBC Driver 13 for SQL Server][SQL Server]Incorrect syntax near '@P1'. `

Any suggestions as to how I can get these queries to work would be a big help!


Solution

  • You can't provide table, field names as parameters; but you can use formatting or string interpolation:

     //TODO: validate tableName and columnName here 
     //since formatting / string interpolation prone to SQL injection
     // e.g. 
     // if (!Regex.IsMatch(tableName, "^[A-Za-z][A-Za-z0-9_]*$")) {/* wrong table */}
    
     using (OdbcCommand delCmd = new OdbcCommand(
       $"ALTER TABLE {tableName} DROP COLUMN {columnName}", 
         dbConnection)) 
     { 
         delCmd.ExecuteNonQuery();
     }