从第n行开始选择n行数

时间:2013-07-29 19:17:36

标签: sql sql-server tsql

这里的SQL-noobie想要将以下存储过程修改为从指定行开始选择指定行数的行。例如,我想从第10行开始选择5行,即10,11,12,13,14,15。

以下是我的SP看起来像atm:

SELECT Posts.Slug, Comments.commentId, Comments.[date], Comments.name, Comments.[text]
FROM Comments 
INNER JOIN Posts ON Comments.postId = Posts.Id
WHERE Comments.approved = 0

我不需要按顺序阅读结果,以便重要。

谢谢!

4 个答案:

答案 0 :(得分:5)

在SQL Server 2005/2008中,您需要使用行号,正如Maurice所说。遗憾的是,LIMIT语法不起作用。查询将如下所示(假设您想按日期排序)

WITH numbered AS
(
    SELECT 
       Posts.Slug, 
       Comments.commentId, 
       Comments.[date],
       Comments.name, Comments.[text],  
       ROW_NUMBER() OVER (ORDER BY date) as rownum
    FROM Comments 
    INNER JOIN Posts ON Comments.postId = Posts.Id
    WHERE Comments.approved = 0
) 
SELECT * FROM numbered WHERE rownum BETWEEN @startrow AND @endrow

以上假设@startrow和@endrow是传递给存储过程的参数。

答案 1 :(得分:4)

如果您正在使用SQL Server 2012,可以使用OFFSETFETCH进行分页,但它们需要ORDER BY子句:

SELECT Posts.Slug, Comments.commentId, Comments.[date], Comments.name, Comments.[text]
FROM Comments 
INNER JOIN Posts ON Comments.postId = Posts.Id
WHERE Comments.approved = 0
ORDER BY [date]
OFFSET 10 ROWS
FETCH NEXT 5 ROWS ONLY

如果不使用SQL Server 2012,ROW_NUMBER()方法就是您应该采用的方法。

如果您真的想要任意排序,可以使用ORDER BY (SELECT 1),但如果没有明确的排序,则无法保证一致性。

答案 2 :(得分:-2)

确实,sql server最快的是

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

看看here

答案 3 :(得分:-3)

在t-sql中使用ROW_NUMBER()函数。见MSDN

USE AdventureWorks2012;
GO
WITH OrderedOrders AS
(
    SELECT SalesOrderID, OrderDate,
    ROW_NUMBER() OVER (ORDER BY OrderDate) AS RowNumber
    FROM Sales.SalesOrderHeader 
) 
SELECT SalesOrderID, OrderDate, RowNumber  
FROM OrderedOrders 
WHERE RowNumber BETWEEN 50 AND 60;