Solved

Retrieving the MAX Value from a SQL Column?

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

Get up to 2TB FREE CLOUD per backup license!

An exclusive Black Friday offer just for Expert Exchange audience! Buy any of our top-rated backup solutions & get up to 2TB free cloud per system! Perform local & cloud backup in the same step, and restore instantly—anytime, anywhere. Grab this deal now before it disappears!

Join & Write a Comment

I have written a PowerShell script to "walk" the security structure of each SQL instance to find:         Each Login (Windows or SQL)             * Its Server Roles             * Every database to which the login is mapped             * The associated "Database User" for this …
SQL Server engine let you use a Windows account or a SQL Server account to connect to a SQL Server instance. This can be configured immediatly during the SQL Server installation or after in the Server Authentication section in the Server properties …
When you create an app prototype with Adobe XD, you can insert system screens -- sharing or Control Center, for example -- with just a few clicks. This video shows you how. You can take the full course on Experts Exchange at http://bit.ly/XDcourse.
You have products, that come in variants and want to set different prices for them? Watch this micro tutorial that describes how to configure prices for Magento super attributes. Assigning simple products to configurable: We assigned simple products…

747 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

12 Experts available now in Live!

Get 1:1 Help Now