SQL 如何运行查询并将结果放入变量中

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2837900/
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-01 06:14:22  来源:igfitidea点击:

How to run a query and put the result into a variable

sqlms-accessvba

提问by l--''''''---------''''''''''''

I am running a query from the VBA editor of Access:

我正在从 Access 的 VBA 编辑器运行查询:

select max(somerow) from sometable

I want to put the result of this query into a VBA variable. How do i do it?

我想将此查询的结果放入 VBA 变量中。我该怎么做?

回答by HansUp

Look at Access Help for DMax function.

查看 DMax 功能的 Access 帮助。

Dim varSomething As Variant
varSomething = DMax("somerow", "sometable")

Edit: I realize that suggestion is not what you were looking for. But it seems to me you may be taking the long way round to achieve something that is simple with the DMax domain function.

编辑:我意识到该建议不是您想要的。但在我看来,使用 DMax 域函数实现一些简单的事情可能需要走很长的路。

回答by marg

If you just want the Max value, you should consider using HansUps Solution.

如果您只想要 Max 值,您应该考虑使用 HansUps 解决方案。

Here is a solution using DAO:

这是使用 DAO 的解决方案:

Dim rs As DAO.Recordset
Dim sqlMax As String
Dim result As Integer

sqlMax = "select max(somerow) from sometable"
Set rs = CurrentDb.OpenRecordset(sqlMax)

If rs.Fields.Count = 1 Then
    result = rs.Fields(0)
End If

Set rs = Nothing

You will need to add a Reference to the Microsoft DAO Object library through Tools->References in the VBA Editor

您将需要通过 VBA 编辑器中的 Tools->References 添加对 Microsoft DAO 对象库的引用