不正确的语法必须声明标量变量
Posted
技术标签:
【中文标题】不正确的语法必须声明标量变量【英文标题】:Incorrect syntax must declare scalar variable 【发布时间】:2016-06-29 17:57:52 【问题描述】:我正在尝试将数据从 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 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)"
【问题讨论】:
问题是变量@Fill Pressure (psi)
和@Empty Weight (lbs)
包含空格和括号。当您声明它们/设置valquery
时尝试剥离它们
我已经尝试过了,但没有帮助。查询如下 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,@FillPressurepsi,@EmptyWeightlbs,@FullWeightlbs,@LiqLiters,@Type,@Size)
【参考方案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)"
【讨论】:
这个还是不行。现在我收到一条错误消息“Psi 附近的语法错误。必须声明标量变量 @FillPressure_psi。 @dotnet 你是如何声明以前的变量的,例如@模型?以上是关于不正确的语法必须声明标量变量的主要内容,如果未能解决你的问题,请参考以下文章