vba adodb参数查询失败
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了vba adodb参数查询失败相关的知识,希望对你有一定的参考价值。
我有一个adodb参数查询失败并返回错误或返回空记录集的问题。但是类似的DAO查询成功。
这都在MS Access中
首先是SQL - Find_Post_Code - 这是为了获取其中一个或两个参数:
PARAMETERS [Local] Text ( 255 ), FState Text ( 255 );
SELECT PCodes.postcode, PCodes.locality, PCodes.state, PCodes.long, PCodes.lat
FROM PCodes
WHERE (((PCodes.locality) Like "*" & [Local] & "*") AND ((PCodes.state)=[FState])) OR (((PCodes.locality) Like "*" & [Local] & "*") AND ((([PCodes].[state]) Like [FState]) Is Null))
ORDER BY PCodes.locality;
现在ADODB功能:
Public Function GetPostCode(varLocality As Variant, varState As Variant) As String
'//Purpose: Return Post Code for a varLocality and/or varState
Dim cmd As New ADODB.Command
Dim rst As New ADODB.Recordset
On Error GoTo Handle_err
With cmd
.CommandText = "Find_Post_Code"
.CommandType = adCmdStoredProc
Set .ActiveConnection = CurrentProject.Connection
.Parameters.Append .CreateParameter("Local", adVarChar, adParamInput, , CStr(Nz(varLocality, "")))
.Parameters.Append .CreateParameter("FState", adVarChar, adParamInput, , CStr(Nz(varState, "")))
rst.CursorType = adOpenStatic
Set rst = .Execute
End With
If Not rst.EOF Then
GetPostCode = rst!postcode
End If
rst.Close
Handle_err:
If Err Then
MsgBox "Error " & Format(Err.Number) & " " & Err.Description, vbCritical, AppTitle
Err.Clear
End If
Set rst = Nothing
Set cmd = Nothing
End Function
此操作失败,并显示错误消息:错误3708参数对象未正确定义。提供的信息不一致或不完整。
如果我将参数转换为adBSTR,则没有错误,但结果记录集没有数据
但是,如果我使用以下DAO功能一切都很好
Public Function GetPostCode2(Locality As String, State As String) As String
'//Purpose: Return Post Code for a varLocality and/or varState
Dim db As Database
Dim qd As DAO.QueryDef
Dim prmLocality As DAO.Parameter
Dim prmFSTate As DAO.Parameter
Dim rst As DAO.Recordset
On Error GoTo Handle_err
Set db = CurrentDb
Set qd = db.QueryDefs("Find_Post_Code")
Set prmLocality = qd.Parameters!Local
prmLocality.Value = Locality
Set prmFSTate = qd.Parameters!FState
prmFSTate.Value = State
Set rst = qd.OpenRecordset
If Not rst.EOF Then
GetPostCode2 = rst!postcode
End If
rst.Close
Handle_err:
If Err Then
MsgBox "Error " & Format(Err.Number) & " " & Err.Description, vbCritical, AppTitle
Err.Clear
End If
Set rst = Nothing
Set prmLocality = Nothing
Set prmFSTate = Nothing
Set qd = Nothing
Set db = Nothing
End Function
我宁愿不在ADODB和DAO之间交换和改变以实现我的目标。非常感谢您的帮助
答案
感谢您的输入。以下是解决方案:1。修改HansUp建议的SQL语句。
PARAMETERS [Local] Text ( 255 ), FState Text ( 255 );
SELECT PCodes.postcode, PCodes.locality, PCodes.state, PCodes.long, PCodes.lat
FROM PCodes WHERE (((PCodes.locality) Like "%" & [Local] & "%") AND ((PCodes.state)=
[FState])) OR (((PCodes.locality) Like "%" & [Local] & "%") AND ((([PCodes].[state])
Like [FState]) Is Null)) ORDER BY PCodes.locality;
有趣的是,如果在Access UI中使用,此查询不会返回任何值
- 将ADO参数转换为adBSTR - adVarChar和adVarWChar都返回错误3708参数对象未正确定义。提供的信息不一致或不完整。
以上是关于vba adodb参数查询失败的主要内容,如果未能解决你的问题,请参考以下文章
VBA ADODB 错误 -2147217904 - 未为某些必需参数指定值
从 MS Access VBA 通过 ODBC 进行 MySQL 查询:ADODB 异步执行不起作用