简体   繁体   English

更改表 SqlCommand

[英]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.我正在尝试使用带参数的 SqlCommand 更改表中一列的数据类型,但它不起作用。 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".但是代码不断抛出错误:“@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?我通常将 SqlCommand 与 select、insert 语句的参数一起使用,但它似乎不适用于 alter 语句?

because by default, tableName and column names CANNOT BE PARAMETERIZED .因为默认情况下, tableName 和列名不能被参数化 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.避免 sql 注入的一种方法是创建一个用户定义函数来检查 tableName 是否有效。 Then concatenate the name on the string.然后连接字符串上的名称。 eg,例如,

Here's the UDF这是 UDF

private bool IsValidColumnNameOrTableName(string tablecolumnName)
{
    // other codes
    return returnValue;
}

You cannot use parameters in DDL statements.不能在 DDL 语句中使用参数。 You should create the statement string dynamically:您应该动态创建语句字符串:

DBSql.ExecSQLStatement(
    "ALTER TABLE " + TableColumnArray[0] + " ALTER COLUMN " + TableColumnArray[1] + " varchar(MAX)",
    dict,connectionStringName);

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 sql server 不允许表名和列名是变量值的语法

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM