【发布时间】:2013-10-14 20:57:35
【问题描述】:
在使用来自 VBA 的 SQL 和参数化查询时,我遇到了以下问题。
我在构造参数的时候,可以分别构造varchar和int参数并正确使用。但是,当我混合它们时,会出现以下 SQL 错误:
Operand type clash: text is incompatible with int
当我组合多种类型的参数时,SQL 似乎将所有内容都粉碎为文本。
我必须对我的代码(VBA/SQL)做哪些不同的处理才能让第三种情况起作用(使用不同类型的参数)?
这是 VBA 代码:
Sub testAdodbParameters()
Dim Cn As ADODB.Connection
Dim Cm As ADODB.Command
Dim Pm As ADODB.Parameter
Dim Pm2 As ADODB.Parameter
Dim Rs As ADODB.Recordset
Set Cn = New ADODB.Connection
Cn.Open "validConnectionString;"
Set Cm = New ADODB.Command
On Error GoTo errHandler
With Cm
.ActiveConnection = Cn
.CommandType = adCmdText
Set Pm = .CreateParameter("TestInt", adInteger, adParamInput)
Pm.value = 1
Set Pm2 = .CreateParameter("TestVarChar", adVarChar, adParamInput, -1)
Pm2.value = "testhi"
'this works
If True Then
.CommandText = "INSERT INTO Test(TestInt) VALUES(?);"
.Parameters.Append Pm
End If
'this also works
If False Then
.Parameters.Append Pm2
.CommandText = "INSERT INTO Test(TestVarChar) VALUES(?);"
End If
'this fails with:
'Operand type clash: text is incompatible with int
If False Then
.Parameters.Append Pm
.Parameters.Append Pm2
.CommandText = "INSERT INTO Test(TestVarChar,TestInt) VALUES(?,?);"
End If
Set Rs = .Execute
End With
errHandler:
Debug.Print Err.Description
End Sub
生成表格的SQL代码如下:
CREATE TABLE Test (
ID int IDENTITY(1,1) PRIMARY KEY,
TestVarChar varchar(50),
TestInt int
);
【问题讨论】:
-
Pm是一个 Int 参数,但看起来您正在将其分配给TestVarChar列。 IE。您的参数已切换到位。 -
将命令文本更改为
.CommandText = "INSERT INTO Test(TestInt, TestVarChar) VALUES(?,?);" -
@TimWilliams 绝对是这样......我怀疑这也将是我更复杂查询的最终问题(这是一个测试示例,显然我在我的最小化中复制了一些类似的有问题的逻辑工作示例...真棒)
标签: sql vba sql-server-2005