简体   繁体   中英

Why do I receive a incorrect syntax error while creating a table in C#

I am trying to create a table with the header which was read from a CSV file:

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();
      }
   }
}

The header in the CSV file is this:

"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"

Whenever I run my application I keep getting this error on this line:

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

Error:

Incorrect syntax near `a123CSV`

How can I resolve the error?

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

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

That is because you are enclosing TABLE_NAME inside single quotes. Use this,

SqlCommand createTable = new SqlCommand("CREATE TABLE " + tab + " ([" + readHeader[p].Replace("\"", "") + "] varchar(MAX))", myConnection);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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