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:
Reference: Row_Number() in TSQL
-- 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;
Comments
Post a Comment