I want use OFFSET and Fetch in my SQL server 2012 query.But without any order by.I can not use order by.Because my sort order will be lost. How can I use OFFSET and Fetch withou
By adding an identity column to the temp table variable
declare @TempTable table([some columns], rownr int identity(1,1) )
INSERT INTO @TempTable [some columns]
select [some columns] from table1 order by col1
INSERT INTO @TempTable [same columns]
select [some columns] from table2 order by col2
An automatic incrementing number is added for each row, in the order in which they are added to the temp table. The inserts don't need to fill this column, so the inserts can remain as they are. The identity column can then be used for the order by:
select * from @TempTable Order by rownr OFFSET 20 ROWS FETCH NEXT 50 ROWS ONLY