我正在尝试创建一个包含从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文件中的标题是:
&#34; NPI&#34;,&#34;实体类型代码&#34;,&#34;替代NPI&#34;,&#34;雇主识别 号码(EIN)&#34;,&#34;提供商组织名称(法律业务 姓名)&#34;,&#34;提供商姓氏(法定名称)&#34;,&#34;提供商优先 名称&#34;,&#34;提供商中间名&#34;,&#34;提供商名称前缀文本&#34;
每当我运行我的应用程序时,我都会在此行中收到此错误:
...
if (exists == null)
{
SqlCommand createTable = new SqlCommand("CREATE TABLE '" + tab + "' ([" + readHeader[p].Replace("\"", "") + "] varchar(MAX))", myConnection);
createTable.ExecuteNonQuery();
...
错误:
Incorrect syntax near `a123CSV`
如何解决错误?
答案 0 :(得分:2)
您需要使用[
和]
而不是单引号来转义表名,即:
"CREATE TABLE [" + tab + "] ([" + readHeader[p].Replace("\"", "") + "] varchar(MAX))"
答案 1 :(得分:1)
这是因为您将TABLE_NAME封闭在单引号内。使用此,
SqlCommand createTable = new SqlCommand("CREATE TABLE " + tab + " ([" + readHeader[p].Replace("\"", "") + "] varchar(MAX))", myConnection);