gpt4 book ai didi

sql - VBA Access SQL SELECT 查询只返回一条记录

转载 作者:行者123 更新时间:2023-12-01 22:41:54 29 4
gpt4 key购买 nike

我在 Access 2010 中使用 VBA,但遇到了一个奇怪的问题。我正在尝试从表中提取记录,但我的 SELECT 查询只返回一条记录。

表中有3条记录,但记录集只取到第一条。

这是我的代码。

Dim cc As String 
Dim DB As Database
Dim rst As recordset
Dim sqlstr As String
Dim e As Integer

cc = CmbClass.Text
If cc = "" Then Exit Sub

sqlstr = "SELECT * FROM Students" 'WHERE CCode ='" & cc & "'"

Set DB = CurrentDb
Set rst = DB.OpenRecordset(sqlstr)
'Debug.Print rst.Fields(0)
e = rst.RecordCount
Debug.Print e
If e = 0 Then Exit Sub

e 的值一直是 1,而不是 3。如您所见,我最初有一个更复杂的 SQL 字符串,但我在尝试排除故障时将其简化为最基本的,但问题仍然存在。有谁知道为什么会这样?

谢谢,

谭。

最佳答案

从内存中你需要发出一个 rst.MoveLast 才能像这样可靠地获取记录数:

sqlstr = "SELECT * FROM Students" 'WHERE CCode ='" & cc & "'"

Set DB = CurrentDb
Set rst = DB.OpenRecordset(sqlstr)
rst.MoveLast
e = rst.RecordCount

您可能还需要考虑使用 SELECT COUNT(*) FROM Students 并从记录集中读取值,而不是通过记录来获取计数。使用此查询应该更有效。

关于sql - VBA Access SQL SELECT 查询只返回一条记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11919844/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com