SQL Server 中的行偏移量

2022-01-31 00:00:00 sql sql-server

SQL Server 中是否有任何方法可以从给定偏移量开始获取结果?例如,在另一种类型的 SQL 数据库中,可以这样做:

Is there any way in SQL Server to get the results starting at a given offset? For example, in another type of SQL database, it's possible to do:

SELECT * FROM MyTable OFFSET 50 LIMIT 25

获得结果 51-75.SQL Server 中似乎不存在此构造.

to get results 51-75. This construct does not appear to exist in SQL Server.

如何在不加载所有我不关心的行的情况下完成此操作?谢谢!

How can I accomplish this without loading all the rows I don't care about? Thanks!

推荐答案

我会避免使用 SELECT *.指定您实际需要的列,即使它可能是所有列.

I would avoid using SELECT *. Specify columns you actually want even though it may be all of them.

SQL Server 2005+

SELECT col1, col2 
FROM (
    SELECT col1, col2, ROW_NUMBER() OVER (ORDER BY ID) AS RowNum
    FROM MyTable
) AS MyDerivedTable
WHERE MyDerivedTable.RowNum BETWEEN @startRow AND @endRow

SQL Server 2000

在 SQL Server 2000 中高效地对大型结果集进行分页

一种更高效的大型结果集分页方法

相关文章