Donate

Get All Records Before The Last Inserted Record In SQL Server T-SQL

In a scenario where you want to show all records before the latest injected record, one solution would be to get the latest date or perhaps tha latest primary key field. But, in cases where there is no primary key defined, there's another solution using Row_Number() in SQL Server. See the two queries below:
-- option 1  
 select Production.Product.ProductID, Name as ID from Production.Product   
  where (ProductID < (Select MAX(ProductID) from Production.Product))  
  order by ProductID desc;
  
 -- option 2  
 WITH ProductsView AS  
 (  
   SELECT ProductID, Name,  
   ROW_NUMBER() OVER (ORDER BY ProductID) AS RowNumber  
   From Production.Product  
 )   
 SELECT ProductID, Name FROM ProductsView  
 WHERE (RowNumber < (select Max(RowNumber) from ProductsView))  
  order by ProductID desc;  
Reference: Row_Number() in TSQL

Comments

Donate

Popular Posts From This Blog

WPF CRUD Application Using DataGrid, MVVM Pattern, Entity Framework, And C#.NET

How To Insert Or Add Emojis In Microsoft Teams Status Message

TypeScript Error Or Bug: The term 'tsc' is not recognized as the name of a cmdlet, function, script file, or operable program.