[英]Pass through query with userinput in access form
我有 Access 前端,它由后端的 SQL Server 提供支持。
我制作了一个需要用户输入的表单,根据输入它应该运行直通查询并应该在子表单中显示结果。 我在互联网上读过这不能通过 sql 命令完成,它需要将 sql 编码包装在 VBA 编码中。
我做了这样的代码:
Private Sub id_AfterUpdate()
Dim MyDb As Database, MyQry As QueryDef
Set MyDb = CurrentDb()
Set MyQry = MyDb.CreateQueryDef("")
MyQry.Connect = "ODBC;DSN=mikecollections;UID=***;PWD=****;DATABASE=mikecollections;"
MyQry.SQL = "select currency.tb_coins.id,documenttype,documentsubtype,documentname" & _
"from currency.tb_coins" & _
"inner join collectibles.tb_documents on tb_coins.id=collectibles.tb_documents.prodid" & _
"where currency.tb_coins.id=[forms]![test_form]![id]"
End Sub
在我在表单的 id 字段中输入值后,此代码应该触发,但没有任何反应。 我不知道如何使这段代码工作。 我是 SQL 和 VBA 的新手,请帮忙!
从逻辑上讲,您不能在 passthru 查询中引用 Access 对象。
所以你的sql应该传递控件的value
,而不是引用控件本身。
如果id
很long
:
MyQry.SQL = "select currency.tb_coins.id,documenttype,documentsubtype,documentname" & _
"from currency.tb_coins" & _
"inner join collectibles.tb_documents on tb_coins.id=collectibles.tb_documents.prodid" & _
"where currency.tb_coins.id= " & [forms]![test_form]![id]
然后您需要添加代码以将该querydef
分配给recordset
,以便读取它。 类似的东西:
set rs = myQry.OpenRecordset
如果您愿意,也可以命名您的 queryDef。 然后它将像任何其他查询一样可用:
Set MyQry = MyDb.CreateQueryDef("someName")
'''specify all properties here...
doCmd.OpenQuery "someName"
我在 sql server 中创建了一个存储过程,并在 access 中创建了一个参数以传递到 sql server 并使其工作。 感谢 Hansup 和 iDevlop 的所有帮助。
Private Sub userinput_AfterUpdate()
Dim qrypass As DAO.QueryDef
Dim rst As DAO.Recordset
Set qrypass = CurrentDb.QueryDefs("qu_test")
qrypass.SQL = _
"exec collectibles.sp_coinsvsdocuments " _
& "@userinput=" _
& Forms!test_form!userinput
End Sub
这是所有 Microsoft Access 的解决方案
只需将以下代码复制到 Microsoft Access 模块中并更改参数
Sub test()
' The "Kim_ZZ_Orderlines" has a string 'arg1' in the sql so we just replace this
' with the new value
RunPassThrough "KIM_ZZ_Orderlines", "Indput value", "10"
End Sub
Sub RunPassThrough(QueryToRun, ArgPrompt, ArgDefault)
' John Henriksen
' 2021-09-23
' Sub procedure to run a Pass-through query with argument
' in the query there must be the string 'Arg1" you want to replace
' e.g. AND APPS.OE_ORDER_LINES_ALL.ATTRIBUTE1 = 'arg1'
arg1 = VBA.InputBox(ArgPrompt, ArgPrompt, ArgDefault)
Dim db As DAO.Database
Dim qry, qryNy As String
Dim qrydefOrginal As DAO.QueryDef
Set db = CurrentDb
Set qdef = db.QueryDefs(QueryToRun)
' Save the original sql
qry = qdef.sql
' Make a new sql, here we search for the string "arg1" and replace with our arg1 value
qryNy = VBA.Replace(qry, "arg1", arg1)
' Set the new sql
qdef.sql = qryNy
DoCmd.OpenQuery QueryToRun
' Set the original sql
qdef.sql = qry
Set qdef = Nothing
Set db = Nothing
End Sub
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.