Is it possible to return the last row of a table in MS SQL Server. I am using an auto increment field for the ID and i want to get the last one just added to join it with something else. Any idea?
Here's the code:
const string QUERY = @"INSERT INTO Questions (ID, Question, Answer, CategoryID, Permission) "
+ @"VALUES (@ID, @Question, @Answer, @CategoryID, @Permission) ";
using (var cmd = new SqlCommand(QUERY, conn))
{
cmd.Parameters.AddWithValue("@Question", question);
cmd.Parameters.AddWithValue("@Answer", answer);
cmd.Parameters.AddWithValue("@CategoryID", lastEdited);
cmd.Parameters.AddWithValue("@Permission", categoryID);
cmd.ExecuteNonQuery();
}
Not safe - could have multiple inserts going on at the same time and the last row you'd get might not be yours. You're better off using SCOPE_IDENTITY() to get the last key assigned for your transaction.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With