vb.net get the last ID and display it

user3105451 picture user3105451 · Jan 10, 2014 · Viewed 9.5k times · Source

i need to get the last ID from a table and display it. I've tried Scope_Identity() but somehow i could not manage to get it. the message box shows nothing.. it's empty. here is my current code:

Try
  myConn.ConnectionString = "Data Source=192.168.2.222;Initial Catalog=test;Persist Security Info=True;User ID=sa;Password=sa;"
  myConn.Open()

  myCmd = New System.Data.SqlClient.SqlCommand("SELECT SCOPE_IDENTITY AS LastId FROM customers", myConn)
  oResult = myCmd.ExecuteScalar()

  If oResult IsNot Nothing Then
    MsgBox(oResult.ToString)
  Else
    MsgBox("No Record Found")
  End If

Catch ex As Exception
  MsgBox(ex.Message)
Finally
  myConn.Close()
End Try

Answer

Al-3sli picture Al-3sli · Jan 10, 2014

If your I'd column is numeric you can use max :

 SELECT MAX(ID) AS LastId FROM customers