C# Alter table通过参数传递数据类型,导致语法错误

C# Alter table通过参数传递数据类型,导致语法错误,c#,sql,visual-studio,C#,Sql,Visual Studio,我正在使用VisualStudio创建一个程序。在这个程序中,我必须查找所有创建的表,并查看列表中的列是否存在,如果不存在,则创建它。为此,我创建了以下变量: Dictionary<string, List<Dictionary<string, string>>> TABLE_DICT //the string saves the name of the table, the list the columns and types List<Diction

我正在使用VisualStudio创建一个程序。在这个程序中,我必须查找所有创建的表,并查看列表中的列是否存在,如果不存在,则创建它。为此,我创建了以下变量:

Dictionary<string, List<Dictionary<string, string>>> TABLE_DICT //the string saves the name of the table, the list the columns and types
List<Dictionary<string, string>> TABLE_LIST = new List<Dictionary<string, string>>(); //list of columns in a table with its type
Dictionary<string, string> DICT = new Dictionary<string, string>(); // name of column and the type of this column

在谷歌搜索,至少是列表中的最后一个,不必出错,或者我相信这一点,但仍然会出错。有什么想法吗?

绑定变量/参数仅用于值,不用于表名。作为应用程序逻辑的一部分,您必须更改表名


除此之外,不能使用参数运行DDL命令。它仅适用于DML(插入、更新、删除或调用存储过程)

DDL语句不能参数化。您需要在代码中连接它。因为你需要这样做,你必须

  • 验证参数,或
  • 绝对确保您的参数是可信的
带有验证的示例代码:

var validator = new Regex(@"^\w+$");
if (new[] { TABLE_kvp.Key, kvp.Key, kvp.Value }.All(validator.IsMatch))
{
    command.CommandText = String.Format("ALTER TABLE {0} ADD COLUMN {1} {2}", 
        TABLE_kvp.Key,
        kvp.Key,
        kvp.Value);   
}

>>
command.CommandText=“更改表格?添加列??”这是无效的CommandText您使用的是什么类型的数据库?您是否先尝试了数据库中的原始sql?这解决了问题,我没有想到要连接代码。谢谢
command.CommandText = "ALTER TABLE ? ADD COLUMN [?] ? NULL";
command.CommandText = "ALTER TABLE ? ADD COLUMN [?] ?";
command.CommandText = "ALTER TABLE [?] ADD COLUMN ? ? ";
command.CommandText = "ALTER TABLE ? ADD COLUMN ? MEMO ";
var validator = new Regex(@"^\w+$");
if (new[] { TABLE_kvp.Key, kvp.Key, kvp.Value }.All(validator.IsMatch))
{
    command.CommandText = String.Format("ALTER TABLE {0} ADD COLUMN {1} {2}", 
        TABLE_kvp.Key,
        kvp.Key,
        kvp.Value);   
}