c# - 为什么在 C# 中创建表时收到不正确的语法错误

标签 c# sql csv

我正在尝试创建一个表,其标题是从 CSV 文件读取的:

myConnection = new SqlConnection(cString);
myConnection.Open();

var lines = File.ReadLines(textBox1.Text);
List<string> readHeader = lines.ElementAt(0).Split(',').ToList();
string tab = "a123CSV";
readHeader.ToArray();
string exists = null;
try
{
   SqlCommand cmd = new SqlCommand("SELECT * FROM sysobjects where name = '" + tab + "'", myConnection);
   exists = cmd.ExecuteScalar().ToString();
}
catch (Exception ce)
{
   exists = null;
}

if (exists == null)
{
   int p;
   for (p = 0; p <= readHeader.Count; p++)
   {
      if (exists == null)
      {
         SqlCommand createTable = new SqlCommand("CREATE TABLE '" + tab + "' ([" + readHeader[p] + "] varchar(MAX))", myConnection);
         createTable.ExecuteNonQuery();
         exists = tab;
      }
      else
      {
         SqlCommand addcolumn = new SqlCommand("ALTER TABLE '" + tab + "' ADD [" + readHeader[p] + "] varchar(MAX)", myConnection);
         addcolumn.ExecuteNonQuery();
      }
   }
}

CSV 文件中的标题是这样的:

"NPI","Entity Type Code","Replacement NPI","Employer Identification Number (EIN)","Provider Organization Name (Legal Business Name)","Provider Last Name (Legal Name)","Provider First Name","Provider Middle Name","Provider Name Prefix Text"

每当我运行我的应用程序时,我都会在这一行收到此错误:

...
if (exists == null)
{
SqlCommand createTable = new SqlCommand("CREATE TABLE '" + tab + "' ([" + readHeader[p].Replace("\"", "") + "] varchar(MAX))", myConnection);
createTable.ExecuteNonQuery();
...

错误:

Incorrect syntax near `a123CSV`

如何解决该错误?

最佳答案

您需要使用[]而不是单引号对表名称进行转义,即:

"CREATE TABLE [" + tab + "] ([" + readHeader[p].Replace("\"", "") + "] varchar(MAX))"

关于c# - 为什么在 C# 中创建表时收到不正确的语法错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24146580/

相关文章:

mysql - 在 SQL 中存储/查询特定树结构有更好的方法吗?

c# - gRPC 与 Asp.net Core Mvc 一起运行

c# - 使用键名从 ModelState 获取值

c# - 使 c# winforms 应用程序可用作非托管 mfc 应用程序的 dll

sql - 我需要编写一个查询来列出所有员工及其下属数量

c# - 附加的 linq 查询的等效 T-SQL 选择查询是什么?

c# - linq to sql无法将时间(小时,分钟)保存到sql server

python - 使用 python 从 csv 数据集中消除不存在/空值

regex - 使用perl拆分csv文件?

python - 将不同长度的数组列表保存到csv