Results 1 to 3 of 3

Thread: [RESOLVED] Obtain the MAX number in SQL ?

  1. #1

    Thread Starter
    Lively Member
    Join Date
    Oct 2005
    Posts
    90

    Resolved [RESOLVED] Obtain the MAX number in SQL ?

    This SQL statement should select the maximum number in the Auto Numbering column ' JOB_no' in my SQL database.


    VB Code:
    1. strSQL = "SELECT MAX(JOB_no)"
    2.         strSQL = strSQL & " FROM JOBS"
    3.         strSQL = strSQL & " WHERE myusername = '" & Nowuser & " '"
    4.  
    5.         Call SQL_SELECTconnection()


    How do I actually 'use' the result in VB.net 2005 ?
    EG MSGBOX (the result of my query?)


    I tried - MsgBox(mydataset.Tables(0).Rows(0)("job_No"))
    (Which works for a normal select statement), but errors when using 'MAX' - stating job_no is not a valid column of table 'table'.

  2. #2
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    111,221

    Re: Obtain the MAX number in SQL ?

    It isn't. Your query is returning a single value, not a column. If you use an aggregate function to get a value you have to specify its name if you want to use it as a column, e.g.
    Code:
    SELECT Max(JobNo) AS MaxJobNo FROM Jobs
    Having said that, if you're just getting a single value from a database then there shouldn't be any DataSets or DataTables involved:
    VB Code:
    1. Dim myConnection As New SqlConnection("connection string here")
    2. Dim myCommand As New SqlCommand("SELECT MAX(job_no) FROM Jobs WHERE myusername = @myusername", myConnection)
    3.  
    4. myCommand.Parameters.AddWithValue("@myusername", Nowuser)
    5. myConnection.Open()
    6.  
    7. Dim result As Object = myCommand.ExecuteScalar()
    8.  
    9. If result Is Nothing Then
    10.     MessageBox.Show("No jobs for specified user.")
    11. Else
    12.     Dim maxJobNo As Integer = CInt(result)
    13.  
    14.     MessageBox.Show("Max job no: " & maxJobNo)
    15. End If
    16.  
    17. myConnection.Close()
    Why is my data not saved to my database? | MSDN Data Walkthroughs
    VBForums Database Development FAQ
    My CodeBank Submissions: VB | C#
    My Blog: Data Among Multiple Forms (3 parts)
    Beginner Tutorials: VB | C# | SQL

  3. #3

    Thread Starter
    Lively Member
    Join Date
    Oct 2005
    Posts
    90

    Re: [RESOLVED] Obtain the MAX number in SQL ?

    Great - Thanks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width