使用 VBA 代码在 Access 中运行 SQL 语句

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21405391/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-12 01:35:17  来源:igfitidea点击:

Run SQL Statement in Access using VBA code

sqlvbams-access

提问by M.Flifl

I can't figure out what is wrong in this, I'm collecting search criteria from a Form to use it in search.

我无法弄清楚这有什么问题,我正在从表单中收集搜索条件以在搜索中使用它。

The SQL line stored like this : (strWhere is the collected info from the Form)

SQL 行存储如下:(strWhere 是从表单中收集的信息)

SQLst = "SELECT Deposits.Fines, Deposits.[Deposit Value], Deposits.[Deposit Date], Deposits.Depositor, Info.Tower, Deposits.[Account Number] FROM Info, Deposits Where " & strWhere & ";"

SQLst = "SELECT Deposits.Fines, Deposits.[Deposit Value], Deposits.[Deposit Date], Deposits.Depositor, Info.Tower, Deposits.[Account Number] FROM Info, Deposits Where " & strWhere & ";"

The final SQL statement looks like this:

最终的 SQL 语句如下所示:

SELECT Deposits.Fines, Deposits.[Deposit Value], Deposits.[Deposit Date], Deposits.Depositor, Info.Tower, Deposits.[Account Number] FROM Info, Deposits Where ([Account Number] = "1234");

选择存款。罚款,存款。[存款价值],存款。[存款日期],存款。存款人,信息塔,存款。[帐号]来自信息,存款地点([帐号] =“1234”);

Now After I run the Line using this command (SQLst is the SQL Line up)

现在在我使用这个命令运行 Line 之后(SQLst 是 SQL Line up)

DoCmd.OpenQuery SQLst

DoCmd.OpenQuery SQLst

I get this message:

我收到这条消息:

enter image description here

在此处输入图片说明

回答by Fionnuala

Not DoCmd.OpenQuery SQLst, that is for saved queries, not SQL strings. You need:

Not DoCmd.OpenQuery SQLst,用于保存的查询,而不是 SQL 字符串。你需要:

' Best to use a separate instance, so you can get record counts etc.
Set db = CurrentDB

For action queries:

对于动作查询:

db.Execute SQLst, dbFailOnerror

For SELECT queries, you can either use a recordset or update or create a query.

对于 SELECT 查询,您可以使用记录集或更新或创建查询。

Set rs = db.Openrecordset(SQLst)

' This query does not exist
Set qdf = db.CreateQueryDef("MyQuery", SQLst)

I doubt that the account number is text, so:

我怀疑帐号是文本,所以:

 ([Account Number] = 1234);

Quotes are used for text-type fields / columns, numbers are as is and dates are delimited with hash (#).

引号用于文本类型的字段/列,数字按原样使用,日期用哈希 (#) 分隔。