[英]MS Access - Writing SQL in VBA
背景
开发一个MS Access模块,该模块在触发onClick()事件时执行SQL代码。
码
Dim sqlString As String
sqlString = "SELECT [Table - Summary - All Item Forecasts, Sales, and POs].[COMPANY ID], " _
& "[Table - Summary - All Item Forecasts, Sales, and POs].[COMPANY NAME], " _
& "[Table - Summary - All Item Forecasts, Sales, and POs].ITEM, " _
& "[Table - Summary - All Item Forecasts, Sales, and POs].STYLE, " _
& "[Table - Summary - All Item Forecasts, Sales, and POs].DESCRIPTION, " _
& "[Table - Summary - All Item Forecasts, Sales, and POs].[SALE PRICE], " _
& "[Table - Summary - All Item Forecasts, Sales, and POs].[ON-HAND QTY], " _
& "[Table - Summary - All Item Forecasts, Sales, and POs].[FORECAST QTY], " _
& "[Table - Summary - All Item Forecasts, Sales, and POs].[MaxOfLATEST PO DATE] " _
& "FROM [Table - Active Product Catalog] " _
& "LEFT JOIN [Table - Summary - All Item Forecasts, Sales, and POs] " _
& "ON [Table - Active Product Catalog].STYLE = [Table - Summary - All Item Forecasts, Sales, and POs].STYLE " _
& "GROUP BY [Table - Summary - All Item Forecasts, Sales, and POs].[COMPANY ID], " _
& "[Table - Summary - All Item Forecasts, Sales, and POs].[COMPANY NAME] , " _
& "[Table - Summary - All Item Forecasts, Sales, and POs].Item, " _
& "[Table - Summary - All Item Forecasts, Sales, and POs].Style, " _
& "[Table - Summary - All Item Forecasts, Sales, and POs].Description, " _
& "[Table - Summary - All Item Forecasts, Sales, and POs].[SALE PRICE], " _
& "[Table - Summary - All Item Forecasts, Sales, and POs].[ON-HAND QTY], " _
& "[Table - Summary - All Item Forecasts, Sales, and POs].[FORECAST QTY], " _
& "[Table - Summary - All Item Forecasts, Sales, and POs].[MaxOfLATEST PO DATE]" _
& "HAVING ((([Table - Summary - All Item Forecasts, Sales, and POs].[COMPANY NAME]) Like ' * ' & [Enter Company Name:] & ' * '));"
DoCmd.RunSQL sqlString
错误
运行时错误'2342':RunSQL操作需要一个由SQL语句组成的参数。
问题
[Enter Company Name:]
”)。 我不太确定这是否会引发SQL语句,但是如前所述,该语法在MS Access中运行。 即使我用硬编码值替换提示,也会收到相同的错误消息。 注意:我很可能会创建一个inputBox
,询问company name
,然后将变量放在SQL语句的最后一行。
如DoCmd.RunSQL 文档中所述,它用于运行“动作查询”。 也就是说, SQLStatement是
字符串表达式,它是用于操作查询或数据定义查询的有效SQL语句。 它使用INSERT INTO,DELETE,SELECT ... INTO,UPDATE,CREATE TABLE,ALTER TABLE,DROP TABLE,CREATE INDEX或DROP INDEX语句。
请注意,以上列表包括SELECT...INTO
但不包括普通的SELECT
。 要执行普通的SELECT
并返回记录集,您需要执行以下操作
Dim cdb As DAO.Database
Set cdb = CurrentDb
Dim rst As DAO.Recordset
Set rst = cdb.OpenRecordset(sqlString, dbOpenSnapshot)
' loop through the Recordset contents
另外,在最后两行中,您缺少... [MaxOfLATEST PO DATE]和HAVING之间的空格。 尝试将其作为SQL运行时,它将失败。
我自己打了几次,因为我是VBA的新手-我总是在run命令后放一个debug.print SQLstring,因为这样更容易在即时窗口中找到这些丢失的空格等。
HTH,珍妮
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.