简体   繁体   中英

Getting the ID of last inserted row from SQL using C#

I have this code in my application, and it's working fine. I didn't use SCOPE_IDENTITY as I heard its old method. Can anybody check if I am doing the right method for getting last inserted Record ID ? Will this work If I add a transaction ?

using (SqlCommand com = new SqlCommand("INSERT INTO App_Users (UserName, Description) OUTPUT INSERTED.UserID " +
    "VALUES (@pUserName, @pDescription); ", con))
{


    com.Parameters.AddWithValue("@pUserName" ,userNameTxt.Text ); 

    com.Parameters.AddWithValue("@pDescription" , userDescription.Text); 



    int lastID = Convert.ToInt32(com.ExecuteScalar());

    foreach (ListViewItem lit in ListView3.Items)
    {
        HiddenField gid = (HiddenField)lit.FindControl("ListGroupID");
        int gidVal = 0;
        if (gid != null && gid.Value != null && !Int32.TryParse(gid.Value, out gidVal)) gidVal = 0;
        if (gidVal != 0)
        {
            com.CommandText = "INSERT INTO App_UserGroups (UserID, GroupID) " +
                "VALUES ( " +   lastID  + ", " + gidVal + ")";
            com.ExecuteNonQuery();
        }
    }

您可以使用scope_identity:

using (SqlCommand com = new SqlCommand("INSERT INTO App_Users (UserName, Description) " + " VALUES (@pUserName, @pDescription);" + "SELECT CAST(scope_identity() AS int)" , con))

I ran into the same question a few days ago too and i've found this SO post explaining every way of retrieving the inserted id from the table.

To answer your question, both OUTPUT_CLAUSE and IDENT_CURRENT can be used in this scenario even if you add a transaction but i would recomment IDENT_CURRENT because an OUTPUT clause will return rows to the client even if the statement encounters errors and is rolled back .

Use it as @horHay suggested in the comments as :

using (SqlCommand com = new SqlCommand("INSERT INTO App_Users (UserName, Description)"+ "VALUES (@pUserName, @pDescription) SELECT IDENT_CURRENT('App_Users'); ", con))


I would not suggest SCOPE_IDENTITY or @@IDENTITY because it may return wrong values (null) if you're not using SQL Server 2008 R2 SP2 or higher ( source - last row from the page.) especially for your requirement (inserting the value in some other table).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM