Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select the last row in a SQL table

Tags:

sql

sql-server

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(); 
}
like image 805
Ahmad Farid Avatar asked Jul 14 '09 15:07

Ahmad Farid


1 Answers

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.

like image 139
n8wrl Avatar answered Sep 28 '22 06:09

n8wrl