如何在SQL查询中使用变量?

时间:2014-06-05 13:02:47

标签: sql vba access-vba

我进行了查询以获取某列的最大值

sSQLmax = "SELECT MAX([tablename]!rowname) as MaxNum FROM [tablename]"

我想使用MaxNum值。我在一个Msgbox中尝试了它并给了我一个空白值。我尝试了所有这些:

MsgBox "MaxNum" & MaxNum

MsgBox "MaxNum" & sSQLMAX.MaxNum

MsgBox "MaxNum" & sSQLMAX!MaxNum

更多代码

Dim db As DAO.Database, rst As DAO.Recordset
Set db = CurrentDb
Set rst = db.OpenRecordset(sSQLmax)

但没有一个可行,我确定它很简单,但它逃脱了我

2 个答案:

答案 0 :(得分:2)

使用您的代码,您只需将变量设置为字符串。你实际上并没有做任何事情。这可能更符合您的要求:

Dim db As DAO.Database, rst As DAO.Recordset, sSQLmax As String
sSQLmax = "SELECT MAX([tablename].rowname) as MaxNum FROM [tablename]"
Set db = CurrentDb

Set rst = db.OpenRecordset(sSQLmax, dbOpenDynaset)

If (rst.RecordCount <> 0) Then
  rst.MoveFirst
  MsgBox "MaxNumber: " & rst.Fields("rowname")
End If

答案 1 :(得分:0)

尝试DMax功能

Dim result as String
result = DMax("[COLUMN NAME]", "[TABLE NAME]")