2

I am trying to change the datatype of one of the columns in a table using SqlCommand with parameters, but it doesn't work. Here is my code:

    Dictionary<string,string> dict = new Dictionary<string,string>();
    dict.Add("@TableName",TableColumnArray[0].ToString( ));
    dict.Add("@ColumnName",TableColumnArray[1].ToString( ));
    DBSql.ExecSQLStatement( "ALTER TABLE @TableName ALTER COLUMN @ColumnName varchar(MAX)",dict,connectionStringName);

    public static void ExecSQLStatement (string strsql,Dictionary<string,string> dict,string  connectionStringName)
    {
        SqlConnection con = CreateSqlConnectionStr(connectionStringName);
        SqlCommand cmd = new SqlCommand(strsql,con);
        foreach(string dictKey in dict.Keys)
        {
            cmd.Parameters.Add(new SqlParameter(dictKey,dict[dictKey]));
        }
        con.Open( );
        cmd.ExecuteNonQuery( );
        con.Close( );
    }

But the code keeps throwing an error:"Incorrect syntax near @TableName". I cannot find the solution to this problem. I could try to use stored procedures, but I really want to know why the code is not working. I usually use SqlCommand with parameters for select,insert statements, but it seems it doesnt work with alter statements?

coffeeak
  • 2,980
  • 7
  • 44
  • 87

3 Answers3

6

because by default, tableName and column names CANNOT BE PARAMETERIZED. One way you can do to avoid sql injection is to create a User Define Function that check if the tableName is valid or not. Then concatenate the name on the string. eg,

Here's the UDF

private bool IsValidColumnNameOrTableName(string tablecolumnName)
{
    // other codes
    return returnValue;
}
John Woo
  • 258,903
  • 69
  • 498
  • 492
1

You cannot use parameters in DDL statements. You should create the statement string dynamically:

DBSql.ExecSQLStatement(
    "ALTER TABLE " + TableColumnArray[0] + " ALTER COLUMN " + TableColumnArray[1] + " varchar(MAX)",
    dict,connectionStringName);
Mohammad Dehghan
  • 17,853
  • 3
  • 55
  • 72
0

you need specify table name and column name exactly:

"ALTER TABLE " + TableColumnArray[0].ToString( ) + " ALTER COLUMN " + TableColumnArray[1].ToString( ) + "varchar(MAX)"

sql server does not allow syntax where table names and column names are variable values

shibormot
  • 1,638
  • 2
  • 12
  • 23