Solved

Retrieving the MAX Value from a SQL Column?

Posted on 2014-02-27
5
380 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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

PeopleSoft Has Never Been Easier

PeopleSoft Adoption Made Smooth & Simple!

On-The-Job Training Is made Intuitive & Easy With WalkMe's On-Screen Guidance Tool.  Claim Your Free WalkMe Account Now

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
get_systemdrive info from tsql? 1 26
TSQL Challenge... 7 59
T-SQL: I need to add an index on a field 5 50
SQL SERVER 2008 R2 Problem copying database 10 69
Long way back, we had to take help from third party tools in order to encrypt and decrypt data.  Gradually Microsoft understood the need for this feature and started to implement it by building functionality into SQL Server. Finally, with SQL 2008, …
Occasionally there is a need to clean table columns, especially if you have inherited legacy data. There are obviously many ways to accomplish that, including elaborate UPDATE queries with anywhere from one to numerous REPLACE functions (even within…
A short tutorial showing how to set up an email signature in Outlook on the Web (previously known as OWA). For free email signatures designs, visit https://www.mail-signatures.com/articles/signature-templates/?sts=6651 If you want to manage em…
This video shows how to use Hyena, from SystemTools Software, to update 100 user accounts from an external text file. View in 1080p for best video quality.

734 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