Call Last ID VB.NET SQL SERVER

0

I am developing a window to insert data into sqlserver2008 from vb.net, my query is, how to call the maximum id after having saved it

Private Sub btnGuardar_Click(sender As Object, e As EventArgs) Handles btnGuardar.Click
    Try
        Dim command As String = "insert into cargos (idcargo,cargodesc)values(@id,@desc)"
        executequery(command)
        MsgBox("Guardado correctamente", MsgBoxStyle.Information, AcceptButton)
    Catch ex As Exception
        MsgBox(ex.Message)
    End Try
    tbId.Clear()
    tbCargoDesc.Clear()
    ULTIMOREG()
    btnNuevo.Enabled = True
    btnGuardar.Enabled = False
    btnNuevo.Focus()
End Sub
Public Sub executequery(ByVal query As String)
    Dim command As New SqlCommand(query, con)
    command.Parameters.AddWithValue("@id", tbId.Text)
    command.Parameters.AddWithValue("@desc", tbCargoDesc.Text)
    con.Open()
    command.ExecuteNonQuery()
    con.Close()
End Sub
    
asked by Derlis Cabrera 21.09.2017 в 17:06
source

1 answer

-1

You should execute the SELECT SCOPE_IDENTITY () statement in case the Id field is Identity, within the same query in which you make the insert that returns the last inserted id and from VB.Net execute it in the following way to capture that id.

sql = "INSERT INTO...;SELECT SCOPE_IDENTITY()..." 
Dim id = sqlCommand.ExecuteScalar(sql)
    
answered by 21.09.2017 в 17:12