What is the best way to fetch records batch-wise from SQL Server

99封情书 提交于 2019-11-30 13:28:53

If you can't use OFFSET-FETCH in SQL Server 2012 and assuming the table has a primary key or column(s) that allow you to uniquely identify a row, lets call it UniqueKey, then in 2005 upwards you could use ROW_NUMBER like this...

SELECT UniqueKey, col2, col3 
FROM 
(
  SELECT UniqueKey, col2, col3, ROW_NUMBER() OVER (ORDER BY UniqueKey) AS RowNum 
  FROM YourTable
) sub
WHERE sub.RowNum BETWEEN @startRow AND @endRow

If you really have no unique key or possibility of adding one then you could use...

ROW_NUMBER() OVER (ORDER BY (SELECT 0))

...to try and preserve the natural order that the records are stored in. But, depending on your data structure, this is not guaranteed to work exactly how you want it to. So, testing the migration would be even more important, but I'm sure you will be doing that anyway ;-)

Makhsut Islamov

If you use MSSQL 2012 try OFFSET-FETCH clause. It is the best solution!

Example: SELECT … ORDER BY orderid OFFSET 25 ROWS fetches only the next 25 rows.

It means this query will return from 25 to 50 records. The ORDER BY clause is mandatory, so if you don't want to use order, use ORDER BY (SELECT NULL)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!