using (SqlConnection connection = new SqlConnection(ConnectionString))
{
string query = "INSERT INTO SocialGroup (created_by_fbuid) VALUES (@FBUID); SELECT CAST(scope_identity() AS int)";
SqlCommand command = new SqlCommand(query, connection);
command.Parameters.AddWithValue("@FBUID", FBUID);
connection.Open();
command.ExecuteNonQuery();
int lastID = (int)command.ExecuteScalar();
}
Without the
SELECT CAST(scope_identity() AS int)
One row is inserted. But since I need the ID from the created row im using scope_identity. However, when I use this, 2 rows are created instead of one.
Did I miss something?
Thanks
The problem in the code you've posted is that you run 2 times the same query... one with ExecuteNonQuery(); and the last with (int)command.ExecuteScalar();
If you try to use only the executeScalar i think you have the result's you want....
Try and hope this helps...
If you want you can use Parameter to retrieve the Identity, like they do in this Article
Try doing
using (SqlConnection connection = new SqlConnection(ConnectionString))
{
string query = "INSERT INTO SocialGroup (created_by_fbuid) VALUES (@FBUID);";
SqlCommand command = new SqlCommand(query, connection);
command.Parameters.AddWithValue("@FBUID", FBUID);
connection.Open();
command.ExecuteNonQuery();
query = "SELECT CAST(scope_identity() AS int)";
command = new SqlCommand(query, connection);
int lastID = (int)command.ExecuteScalar();
}
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.