Ben Gannaway

Ben Gannaway

  • NA
  • 12
  • 0

Retrieve Identifier from database insert

Oct 8 2009 6:40 AM
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)