在MS Access数据库中选择最大值

时间:2019-01-10 21:29:59

标签: vb.net ms-access

我需要在行列中选择最大值。当我打线

(FindCurrentTimeCard = Val(myreader("Row")) 

我得到一个错误:

  

System.IndexOutOfRangeException

代码:

Public Function FindCurrentTimeCard() As Integer
   Dim myconnection As OleDbConnection = New OleDbConnection
   Dim query As String = "Select MAX(Row) from Table2"
   Dim dbsource As String =("Provider=Microsoft.ACE.OLEDB.12.0;DataSource=S:\Docs\PRODUCTION\Shop Manager\Shop_Manager\Shop_Manager\Database2.accdb;")
   Dim conn = New OleDbConnection(dbsource)
   Dim cmd As New OleDbCommand(query, conn)

   Try
        conn.Open()
        Dim myreader As OleDbDataReader = cmd.ExecuteReader()
        myreader.Read()
        FindCurrentTimeCard = Val(myreader("Row"))
        conn.Close()
    Catch ex As OleDbException
        MessageBox.Show("Error Pull Data from Table2")
        FindCurrentTimeCard = 1
    End Try

End Function

Table2

2 个答案:

答案 0 :(得分:0)

问题是,当您评估一个聚合函数(或者实际上是对一个或多个字段执行某些操作的任何表达式)时,除非为该函数的评估结果分配一个别名(例如Expr1000),否则,另有说明。

因此,当您评估SQL语句时:

select max(table2.row) from table2

MS Access将返回分配给别名(例如Expr1000)的结果:

enter image description here

因此,SQL语句不会输出名为Row的列,从而导致您的代码在尝试检索此类列的值时失败:

FindCurrentTimeCard = Val(myreader("Row"))

相反,您应该指定一个可以在代码中引用的别名,例如:

select max(table2.row) as maxofrow from table2

使用您的函数,然后返回与该列关联的值:

FindCurrentTimeCard = Val(myreader("maxofrow"))

答案 1 :(得分:0)

在线评论和解释

Public Function FindCurrentTimeCard() As Integer
    Dim CurrentTimeCard As Integer
    'The Using block ensures that your database objects are closed and disposed
    'even it there is an error
    'Pass the connection string directly to the connection constructor
    Using myconnection As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;DataSource=S:\Docs\PRODUCTION\Shop Manager\Shop_Manager\Shop_Manager\Database2.accdb;")
        Dim query As String = "Select MAX(Row) from Table2"
        Using cmd As New OleDbCommand(query, myconnection)
            Try
                myconnection.Open()
                'since you are only retrieving a single value
                'you can used .ExecuteScalar which gets the value
                'in the first row, first column
                CurrentTimeCard = CInt(cmd.ExecuteScalar)
            Catch ex As OleDbException
                MessageBox.Show("Error Pull Data from Table2")
            End Try
        End Using
    End Using
    'vb.net uses the Return statement to return the value of the function
    Return CurrentTimeCard
End Function