【问题标题】:Datatable column name omits names starting with a number数据表列名省略以数字开头的名称
【发布时间】:2014-11-02 15:02:20
【问题描述】:

所以我的sql查询是

  List<string> names = new List<string>();    
  cmd = new SqlCommand("Select " + string.Join(",", names) + " from test");
  da = new SqlDataAdapter(cmd);
  dt = new DataTable();
  da.Fill(dt);

当它填充数据表时,有以数字开头的列名,它省略了数字,只在后面打印文本

例如, 如果列名是“1AB2C” 它变成了“AB2C”。 谁能告诉我为什么会发生这种情况以及在哪里修改?

【问题讨论】:

  • 用 [ 和 ] 填充列例如:[1AB2C]

标签: c# sql .net sql-server datatable


【解决方案1】:

试试这个

List<string> names = new List<string>();
            names.Add("[1col]"); //you may write your
            names.Add("name");
            string[] arr = names.ToArray();
            SqlConnection conn = new SqlConnection(ConnectionString);
            conn.Open();
            SqlCommand cmd = new SqlCommand("Select " + String.Join(",", arr) + " from test");

【讨论】:

    【解决方案2】:

    根据 SQL 标准,表名不能以数字开头。 有关详细信息,请参阅此帖子:Table or column name cannot start with numeric?

    【讨论】:

    • 你必须在表名前使用引号`。例如:SELECT * FROM `2names `
    • 或者您可以更改您的命名约定。例如,您可以在表名之前使用和下划线或像“tbl_”这样的前缀
    • 我真的做不到。它实际上是一个数据值。
    • 我确实使用了单引号。但这不起作用,数据表现在没有任何列名。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-27
    • 2018-02-23
    相关资源
    最近更新 更多