我正在尝试编写一个 VBA 函数,该函数返回一组可在 SQL 语句中使用的记录。
这是我尝试过的:
Public Function GetYieldForContainer(code As String, fldName As String) As DAO.Recordset
Dim db As DAO.Database
Dim strSQL As String
Set db = CurrentDb
sqlStr = "SELECT batch_id, yield as " & fldName & " FROM BatchYield WHERE container_id = " & code
Set GetYieldForContainer = db.OpenRecordset(strSQL)
End Function
然后我在 SQL 语句中调用它,如下所示:
SELECT * FROM GetYieldForContainer("J", "jars");
Access 显示错误“FROM 子句中存在语法错误”。这不是很有帮助;我猜测类型不匹配,但我不知道应该使用什么类型。有人知道如何让它发挥作用吗?
对于上下文,我正在尝试编写 VBA 函数,因为我需要对结果记录集执行多个 LEFT JOIN,而 Access 在 SQL 中的嵌套功能非常有限。
Access SQL 中的表和字段名称必须是文字。
你可以这样做:
Public Function GetYieldForContainerSql(code As String, fldName As String) As String
Dim strSQL As String
sqlStr = "SELECT batch_id, yield as " & fldName & " FROM BatchYield WHERE container_id = '" & code & "'"
GetYieldForContainerSql = sqlStr
End Function
然后构建最终的 SQL:
code = "J"
fldName = "jars"
SQL = "SELECT * FROM (" & GetYieldForContainerSql(code, fldName) & ") As T"
然后将此 SQL 应用于查询:
SomeQueryDef.SQL = SQL
在这种情况下,可以减少/缩短为:
SomeQueryDef.SQL = GetYieldForContainerSql("J", "jars");