我正在尝试创建一个表,其标题是从 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/