Get last inserted id SQL server C#

You simply need to issue the select @@identity command to SQL Server, and it’ll return a one-field response that contains the last identity number added during your connection

public void GetLastIdentity()
    {
        int MyIdentityValue;
        // Setup sample connection and command
        SqlClient.SqlConnection objConnection = new SqlClient.SqlConnection("server=NEMEAN;database=MYDATABASE;" + "user ID=USERID;password=PWD");
        SqlClient.SqlCommand objCommand = new SqlClient.SqlCommand("INSERT INTO author (authorname) " + "VALUES('Karl Moore')");
        // Open connection and execute INSERT command
        objConnection.Open();
        objCommand.Connection = objConnection;
        // Execute and check minimum of one record affected...
        if (objCommand.ExecuteNonQuery > 0 == true)
        {
            // Setup separate command to retrieve identity value
            SqlClient.SqlCommand objIdentifier = new SqlClient.SqlCommand("Select @@Identity", objConnection);
            try
            {
                // Return value of field
                MyIdentityValue = objIdentifier.ExecuteScalar;
            }
            catch
            {
                MyIdentityValue = 0;
            }
        }
    }
}

Post a Comment

Please do not post any spam link in the comment box😊

Previous Post Next Post

Blog ads

CodeGuru