简体   繁体   中英

Using Select Scope_Identity() with a store procedure

I am writing some code that would insert user data into database using a stored procedure (sp_AddNewUser). The stored procedure just inserts into the data into the database. I was wondering if I could use SCOPE_IDENTITY() function with a stored procedure without editing the stored procedure.

  SqlCommand cmd = new SqlCommand("sp_AddNewUser", conn);
  cmd.CommandType = CommandType.StoredProcedure;
  cmd.Parameters.Add("@firstname", SqlDbType.VarChar).Value =   row.Cells[_dicDef["firstname"]].Value;
  cmd.Parameters.Add("@lastname", SqlDbType.VarChar).Value = row.Cells[_dicDef["lastname"]].Value;
  cmd.ExecuteNonQuery();
  //NOT SURE WHAT TO DO AFTER THIS COMMENT ----
  string sql = "SELECT CAST(scope_identity() AS int)";
  cmd = new SqlCommand(sql, conn);
  newID = (Int 32_cmd.ExecuteScalar(); //<---- will this return the latest id?

}

No, you cannot use it this way. As MSDN states:

Returns the last identity value inserted into an identity column in the same scope . A scope is a module: a stored procedure, trigger, function, or batch. Therefore, two statements are in the same scope if they are in the same stored procedure, function, or batch.

It won't work for you as your two statements are not in the same scope and SCOPE_IDENTITY() doesn't return anything.

Using @@IDENTITY in this case will return the value you need:

@@IDENTITY will return the last identity column value inserted across any scope in the current session

You have to be careful though to make sure it is the proper identity (should be ok in the example above).

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