2

如何使用 SQL 查询加载第 n 到第 n 条记录?

就像是

select 10 to 20 columnname from tbl order by columnname
4

2 回答 2

4

SQL Server 2012 有一个名为OFFSETand的新功能FETCH

SELECT (list of columns)
FROM YourTable
ORDER BY columnName
  OFFSET 10 ROWS 
  FETCH NEXT 10 ROWS ONLY

http://www.kodyaz.com/sql-server-2012/sql-paging-in-sql-server-2012-sql-order-by-offset-fetch-next-rows.aspx

在 2012 年之前的版本中,最好的方法是使用带有ROW_NUMBER()函数的 CTE(公用表表达式)并使用行号从该 CTE 中进行选择 -在此处查看更多详细信息

于 2012-10-03T16:44:11.140 回答
0

对于 SQL 2005 及更高版本,您可以使用ROW_NUMBER()

 DECLARE @p0 Int = 10
 DECLARE @p1 Int = 10

 SELECT [t1].[pkCompanyID]
 FROM (
     SELECT ROW_NUMBER() OVER (ORDER BY [t0].[pkCompanyID]) AS [ROW_NUMBER], [t0].[pkCompanyID]
     FROM [tblCompany] AS [t0]
     ) AS [t1]
 WHERE [t1].[ROW_NUMBER] BETWEEN @p0 + 1 AND @p0 + @p1
 ORDER BY [t1].[ROW_NUMBER]
于 2012-10-03T16:46:20.323 回答