在使用来自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
);
答案 0 :(得分:0)
您在查询中处于VARCHAR,INT顺序,您可以尝试这样:
.Parameters.Append Pm2
.Parameters.Append Pm
.CommandText = "INSERT INTO Test(TestVarChar,TestInt) VALUES(?,?);"
有效吗?