7
Answers

Retrieve Identifier from database insert

Ask a question
Ben Gannaway

Ben Gannaway

14y
2.7k
1
I need to retrieve the identifier ID from an insert  query so that I can associate it with another table.  I'm using the scope_identity() method, but can't find out how to assign that to a variable so it can be used.  So far I have:

 Console.WriteLine("Opening database");
SqlCommand myCommand = new SqlCommand("INSERT INTO entries(text, name, screen_name, user_id, posi_score)"+"VALUES(@txt,@nm,@scrNm,@uid,@posi_score)select scope_identity() as @identity", myConnection);
myCommand.Parameters.AddWithValue("@txt", txt);
myCommand.Parameters.AddWithValue("@nm", nm);
myCommand.Parameters.AddWithValue("@scrNm", scrNm);
myCommand.Parameters.AddWithValue("@uid", uid);
myCommand.Parameters.AddWithValue("@posi_score",posiScore);

myConnection.Open();
myCommand.ExecuteNonQuery();


myConnection.Close();
Console.WriteLine("Closing database connection");


Answers (7)