coffeeak
coffeeak

Reputation: 3120

Alter table SqlCommand

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?

Upvotes: 2

Views: 3077

Answers (3)

shibormot
shibormot

Reputation: 1638

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

Upvotes: 0

Moha Dehghan
Moha Dehghan

Reputation: 18443

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);

Upvotes: 1

John Woo
John Woo

Reputation: 263703

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;
}

Upvotes: 6

Related Questions