在使用来自 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
);