语法不正确必须声明标量变量

时间:2016-06-29 17:57:53

标签: .net sql-server ado.net ms-access-2007

我正在尝试将数据从MS Access复制到SQL Server数据库。

其中一列的名称为Fill Pressure (psi),导致SQL Server出现问题。我收到以下错误:

  

"" Psi"附近的语法不正确必须声明标量变量@fill。

代码如下

 Dim Cmd As New SqlClient.SqlCommand
 Cmd.Connection = sqlConnection

 For Each dc As DataColumn In AccessTable.Columns
     colquery = colquery + "[" + dc.ColumnName + "],"
     valquery = valquery + "@" + dc.ColumnName + ","
     Cmd.Parameters.AddWithValue("@" + dc.ColumnName, dr(dc.ColumnName))
 Next

 colquery = colquery.Substring(1, colquery.Length - 1)
 valquery = valquery.Substring(1, valquery.Length - 1)

 colquery = colquery + ")"
 valquery = valquery + ")"
 Sqlquery = colquery + valquery
 Sqlquery = Replace(Sqlquery, ",)", ")")

 Cmd.Connection = sqlConnection
 Cmd.CommandType = CommandType.Text
 Cmd.CommandText = Sqlquery

 Dim sqlcommand1 As SqlClient.SqlCommand = New SqlClient.SqlCommand("SET IDENTITY_INSERT  [" + TableName + "]  ON", sqlConnection)
 sqlcommand1.ExecuteNonQuery()
 Cmd.ExecuteNonQuery()

 Dim sqlcommand2 As SqlClient.SqlCommand = New SqlClient.SqlCommand("SET IDENTITY_INSERT [" + TableName + "] OFF", sqlConnection)
 sqlcommand2.ExecuteNonQuery()

来自watch的insert语句的示例。我已经尝试更换空间和"("和")"用空字符串但它不起作用。

"INSERT INTO [dbo].[tblVesselTypes] ([VesselType_ID], [Manufacturer],[Model], [Fill Pressure (psi)], [Empty Weight (lbs)], [Full Weight (lbs)], [Liq Liters], [Type], [Size])
VALUES (@VesselType_ID, @Manufacturer, @Model, @Fill Pressure (psi), @Empty Weight (lbs), @Full Weight (lbs), @Liq Liters, @Type, @Size)"

1 个答案:

答案 0 :(得分:1)

在MS Sql中使用@Fill Pressure (psi)这样的名称变量是不可能的。如果@Fill是一个变量名,Pressure (psi)是未知的命令或类型(用于变量声明)或其他东西,SQL Server会解析 - 无论如何错误。

请参阅MS SQL中不同类型对象的命名约定:
https://msdn.microsoft.com/en-us/library/ms175874.aspx

变量名称中不能包含空格或括号。虽然对象名称可以用方括号或引号括起来。

可能的变量名称是,例如:@FillPressure_psi

所以整个插入语句看起来像:

"INSERT INTO [dbo].[tblVesselTypes] ([VesselType_ID], [Manufacturer],[Model], [Fill Pressure (psi)], [Empty Weight (lbs)], [Full Weight (lbs)], [Liq Liters], [Type], [Size])
VALUES (@VesselType_ID, @Manufacturer, @Model, @FillPressure_psi, @EmptyWeight_lbs, @FullWeight_lbs, @Liq Liters, @Type, @Size)"