简体   繁体   中英

I'm having some issues with my scope identity retrieving a ID from an identity column

I'm having some issues with my scope identity retrieving a ID from an identity column.

This is my code:

cmd = connection.CreateCommand();
cmd.CommandText = "Insert Into oc_manufacturer (name, sort_order) Values(@name, @sort_order);SELECT CAST(scope_identity() AS int)";
cmd.Parameters.AddWithValue("@name", sManufacturer);
cmd.Parameters.AddWithValue("@sort_order", 0);
iManufacturerID = (int)cmd.ExecuteScalar();

cmd.ExecuteNonQuery();

This is inside a try catch. and it hits my catch when i step through it at the 2nd last line of code. I am still very new to using this scope identity. Usually i would create a whole new select statement with the same variables as my insert statement. But that is very long so truing to get this right. any help?

Perhaps I am wrong, but you have marked your question as MySql. In that database system, you retrieve the last inserted autoincrement value with LAST_INSERT_ID() function

cmd.CommandText = @"Insert Into oc_manufacturer (name, sort_order) 
                    Values(@name, @sort_order);
                    SELECT LAST_INSERT_ID()";

Also there is no need to call ExecuteNonQuery, the call to ExecuteScalar will work on both statements but will return the value of the last SELECT

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