Tutorial :How to get the last tuple from a table with SQL Server 2008 R2?



Question:

I want to get a field from the last tuple I have inserted to a table using SQL Server 2008 R2?


Solution:1

Basically, what you need to do is:

SELECT TOP 1 (list of fields)  FROM dbo.YourTable  ORDER BY (some column) DESC  

You need to define how to order the data so that you get the "latest" . If you sort by string, int or datetime, you'll probably want to sort in a descending order to get the most recent first.

Since you didn't provide any table structure or field names at all, this is the best we can do..... next time: please ask a bit more focused - provide more details! We're good programmer - but not mind readers. We don't know your system or your database or your setup - you need to tell us.


Solution:2

There is no way without an identity or "inserteddateTime" column to find this out. A table is an unordered collection of data and only an ORDER BY will impart an definitive ordering. You can not rely on anything else.

SELECT TOP 1 *  FROM MyTable  ORDER BY Whatever DESC  

Can you explain more about the bigger picture please?


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »