I am trying to retrieve a maximum value from sql – vb.net
This is my code: I get this error:
Unable to cast object of type ‘System.DBNull’ to type
‘Oracle.DataAccess.Client.OracleDataReader’
Please help. 🙁
Dim cmd2 As New OracleCommand
cmd2.Connection = conn
'SELECT MAX(LASTNO) FROM d001005 where lbrcode = '104' and CODE1 = 'CASH' and lnodate = '14-NOV-08'
Dim datepara As String = Date.Now.ToString("dd-MMM-yy")
'datepara = "14-NOV-08"
cmd2.CommandText = "SELECT MAX(LASTNO) FROM d001005 where lbrcode = '" + lbr + "' and CODE1 = 'CASH' and lnodate = '" + datepara + "'"
cmd2.CommandType = CommandType.Text
Dim dr2 As OracleDataReader = cmd2.ExecuteScalar
Dim result As Decimal = dr2.Item("LASTNO")
There is no item with the name “LASTNO” as you are using an aggregate function to find out the maximum value. Furthermore ExecuteScalar returns the first value of the first row! Another point is, that you should use OracleParameter for any kind of dynamic statement, to prevent SQL injection!