How to read the last row with SQL Server

后端 未结 17 748
别那么骄傲
别那么骄傲 2020-11-29 03:40

What is the most efficient way to read the last row with SQL Server?

The table is indexed on a unique key -- the \"bottom\" key values represent the last row.

相关标签:
17条回答
  • 2020-11-29 04:17

    In order to retrieve the last row of a table for MS SQL database 2005, You can use the following query:

    select top 1 column_name from table_name order by column_name desc; 
    

    Note: To get the first row of the table for MS SQL database 2005, You can use the following query:

    select top 1 column_name from table_name; 
    
    0 讨论(0)
  • 2020-11-29 04:17
    SELECT * from Employees where [Employee ID] = ALL (SELECT MAX([Employee ID]) from Employees)
    
    0 讨论(0)
  • 2020-11-29 04:19

    I am pretty sure that it is:

    SELECT last(column_name) FROM table
    

    Becaause I use something similar:

    SELECT last(id) FROM Status
    
    0 讨论(0)
  • 2020-11-29 04:20

    If you don't have any ordered column, you can use the physical id of each lines:

    SELECT top 1 sys.fn_PhysLocFormatter(%%physloc%%) AS [File:Page:Slot], 
                  T.*
    FROM MyTable As T
    order by sys.fn_PhysLocFormatter(%%physloc%%) DESC
    
    0 讨论(0)
  • 2020-11-29 04:24

    You can use last_value: SELECT LAST_VALUE(column) OVER (PARTITION BY column ORDER BY column)...

    I test it at one of my databases and it worked as expected.

    You can also check de documentation here: https://msdn.microsoft.com/en-us/library/hh231517.aspx

    0 讨论(0)
  • 2020-11-29 04:27

    If you're using MS SQL, you can try:

    SELECT TOP 1 * FROM table_Name ORDER BY unique_column DESC 
    
    0 讨论(0)
提交回复
热议问题