如何使用SQL查询加载第n行到第m行?

时间:2012-10-03 16:41:43

标签: sql sql-server

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

这样的东西
select 10 to 20 columnname from tbl order by columnname

2 个答案:

答案 0 :(得分:4)

SQL Server 2012有一项名为OFFSETFETCH的新功能:

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中选择 - see more details here

答案 1 :(得分: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]