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

Sunday, June 19, 2016

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.

No comments:

Post a Comment