Tech Junkie Blog - Real World Tutorials, Happy Coding!: ASP.NET: Getting The Inserted ID Back With Scope_Identity()

Saturday, August 31, 2019

ASP.NET: Getting The Inserted ID Back With Scope_Identity()

When you need to do an insert into multiple database table you need to the get the ID of the insert so that you could use that ID for the next insert. Here is how you would do that with the Scope_Identity()which gets the last inserted ID back to you if you execute your query with the ExecuteScalar() method.

                SqlCommand cmd = new SqlCommand("INSERT INTO Users (" +
                    "LoginName," +
                    "FirstName," +
                     "LastName," +
                     "Password," +
                     "Email," +
                     "DOB," +
                     "Sex" +
                     ") VALUES (" +
                    "@Email," +
                    "@FirstName," +
                     "@LastName," +
                     "@Password," +
                     "@Email," +
                     "@DOB," +
                     "@Sex)" + 
                     " Select Scope_Identity();",conn);




Here is how you would execute the query:
int UserId = (int)cmd.ExecuteScalar();


Most of the time you will need to use the Scope_Identity() when you have to deal with foreign key constraints, that's why a Users table is a good example.

2 comments:

  1. Thanks for sharing such an Amazing information, I Couldn't leave without reading your blog. I have read another good blog, I think you have read it too. click here Trend Micro bellen

    ReplyDelete
  2. Thanks for sharing informative content…Find noida software company to know more and Contact us on given no.…

    ReplyDelete

Search This Blog