Solved

Retrieving the MAX Value from a SQL Column?

Posted on 2014-02-27
5
372 Views
Last Modified: 2014-02-27
I am trying to retrieve a MAX value from a column in a table. The issue is if the table contains NO records...I get an error saying:

"Conversion from type 'DBNULL' to type 'Integer' is not valid"

I understand why I get the error because it's returning a NULL value. I'm just not sure how to structure the statement. I know how to return a MAX value in a populated table, just not in an empty table.

    Public Function GetMaxID(ByVal tbl As String, ByVal keyFld As String, ByRef EH As ErrorHandling.ErrorHandler)
        Try
            DBConnection(EH)

            If EH.Bool Then
                sSQL = "SELECT MAX(ISNULL(" & keyFld & ",0)) + 1 FROM " & tbl
                cmd = New SqlCommand(sSQL, cnn)
                EH.Number = cmd.ExecuteScalar()
            End If

        Catch ex As Exception
            EH.ErrorMessage = "GetMaxID() - " & ex.Message & "...Contact Engineering!" & "~E"
        Finally
            cnn.Dispose()
        End Try

        Return EH
    End Function

Open in new window

0
Comment
Question by:BlakeMcKenna
  • 2
  • 2
5 Comments
 
LVL 65

Expert Comment

by:Jim Horn
ID: 39892134
>ByVal keyFld As String
>MAX(ISNULL(" & keyFld & ",0))
The problem you're having here is that you're trying to do a MAX() on a character data type, which means anything other than numbers (NULL, 'banana', '1st place') is going to throw an error, if not during the MAX then definately during the + 1.

I recommend two things.
Change keyFld to ISNULL(keyFld, 0) to convert NULLs to zeros
Filter out these values by adding this to your query
WHERE ISNUMERIC(keyFld) = 1
0
 
LVL 142

Accepted Solution

by:
Guy Hengel [angelIII / a3] earned 500 total points
ID: 39892145
move the IsNull to outside the MAX function, and it should work ...
 sSQL = "SELECT ISNULL ( MAX( " & keyFld & ",0)) + 1 FROM " & tbl
0
 

Author Comment

by:BlakeMcKenna
ID: 39892159
Here is the new statement and it doesn't return anything!

Select ISNULL(ID,0) As MaxValue
  From [Temp]
 Where ISNUMERIC(ID) = 1

Open in new window

0
 

Author Closing Comment

by:BlakeMcKenna
ID: 39892168
Thanks Guy...that worked!
0
 
LVL 142

Expert Comment

by:Guy Hengel [angelIII / a3]
ID: 39894109
please show the output of this query:
Select id, ISNUMERIC(ID) 
  From [Temp] 

Open in new window


rereading the question, I think you are anyhow heading into a wrong direction.
it looks like you want to use a "IDENTITY" field instead of doing this yourself ...
http://technet.microsoft.com/en-us/library/aa933196%28v=sql.80%29.aspx
0

Featured Post

PRTG Network Monitor: Intuitive Network Monitoring

Network Monitoring is essential to ensure that computer systems and network devices are running. Use PRTG to monitor LANs, servers, websites, applications and devices, bandwidth, virtual environments, remote systems, IoT, and many more. PRTG is easy to set up & use.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Audit has been really one of the more interesting, most useful, yet difficult to maintain topics in the history of SQL Server. In earlier versions of SQL people had very few options for auditing in SQL Server. It typically meant using SQL Trace …
Hi all, It is important and often overlooked to understand “Database properties”. Often we see questions about "log files" or "where is the database" and one of the easiest ways to get general information about your database is to use “Database p…
This Micro Tutorial will give you a basic overview how to record your screen with Microsoft Expression Encoder. This program is still free and open for the public to download. This will be demonstrated using Microsoft Expression Encoder 4.
Internet Business Fax to Email Made Easy - With eFax Corporate (http://www.enterprise.efax.com), you'll receive a dedicated online fax number, which is used the same way as a typical analog fax number. You'll receive secure faxes in your email, fr…

896 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

13 Experts available now in Live!

Get 1:1 Help Now