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?

0

3 Answers 3

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;
}
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks for the help. I will be looking into that!
Interesting... maybe provide a link to some documentation that explains why there is this constraint on parameters?
Votes up for the idea because I was trying to avoid sql injection by not using string concatenations.
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);

Comments

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

1 Comment

I don't want to use string concatenations. Thanks for replying though

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.