Solved

Retrieving the MAX Value from a SQL Column?

Posted on 2014-02-27
5
378 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 143

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 143

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

Best Practices: Disaster Recovery Testing

Besides backup, any IT division should have a disaster recovery plan. You will find a few tips below relating to the development of such a plan and to what issues one should pay special attention in the course of backup planning.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
Challenging SQL Update 5 49
MS SQL Delete Query 9 37
Master DB with Masterkey 1 35
SQL - format decimal in a string 5 40
In this article I will describe the Backup & Restore method as one possible migration process and I will add the extra tasks needed for an upgrade when and where is applied so it will cover all.
Ever needed a SQL 2008 Database replicated/mirrored/log shipped on another server but you can't take the downtime inflicted by initial snapshot or disconnect while T-logs are restored or mirror applied? You can use SQL Server Initialize from Backup…
This video shows how to quickly and easily add an email signature for all users on Exchange 2016. The resulting signature is applied on a server level by Exchange Online. The email signature template has been downloaded from: www.mail-signatures…

828 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