Equivalent of LIMIT and OFFSET for SQL Server?(SQL Server 的 LIMIT 和 OFFSET 等价物?)
问题描述
在 PostgreSQL 中有 Limit
和 Offset
关键字,它们将允许非常容易地对结果集进行分页.
In PostgreSQL there is the Limit
and Offset
keywords which will allow very easy pagination of result sets.
SQL Server 的等效语法是什么?
What is the equivalent syntax for SQL Server?
推荐答案
LIMIT
的等价物是 SET ROWCOUNT
,但如果你想要通用分页,最好写一个查询如下:
The equivalent of LIMIT
is SET ROWCOUNT
, but if you want generic pagination it's better to write a query like this:
;WITH Results_CTE AS
(
SELECT
Col1, Col2, ...,
ROW_NUMBER() OVER (ORDER BY SortCol1, SortCol2, ...) AS RowNum
FROM Table
WHERE <whatever>
)
SELECT *
FROM Results_CTE
WHERE RowNum >= @Offset
AND RowNum < @Offset + @Limit
这里的优点是偏移和限制的参数化,以防您决定更改分页选项(或允许用户这样做).
The advantage here is the parameterization of the offset and limit in case you decide to change your paging options (or allow the user to do so).
注意:@Offset
参数应该为此使用从一开始的索引,而不是正常的从零开始的索引.
Note: the @Offset
parameter should use one-based indexing for this rather than the normal zero-based indexing.
这篇关于SQL Server 的 LIMIT 和 OFFSET 等价物?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:SQL Server 的 LIMIT 和 OFFSET 等价物?


基础教程推荐
- 无法在 ubuntu 中启动 mysql 服务器 2021-01-01
- 将数据从 MS SQL 迁移到 PostgreSQL? 2022-01-01
- SQL Server:只有 GROUP BY 中的最后一个条目 2021-01-01
- 在 VB.NET 中更新 SQL Server DateTime 列 2021-01-01
- Sql Server 字符串到日期的转换 2021-01-01
- 使用pyodbc“不安全"的Python多处理和数据库访问? 2022-01-01
- 如何在 SQL Server 的嵌套过程中处理事务? 2021-01-01
- SQL Server 中单行 MERGE/upsert 的语法 2021-01-01
- SQL Server 2016更改对象所有者 2022-01-01
- ERROR 2006 (HY000): MySQL 服务器已经消失 2021-01-01