在SQL中分页,如何在where子句中使用row_number?

时间:2015-01-16 08:14:58

标签: sql sql-server tsql stored-procedures

我试图在SELECT查询的where子句中使用MSSQL中的行号(在存储过程中)但是它不允许我在where子句中引用该列。你通常会怎么做这件事?

我正在尝试以下(不起作用):

SELECT ROW_NUMBER() OVER(ORDER BY [dtd]) AS row_num, [data]
FROM dbo.Reports INNER JOIN dbo.Types
WITH (NOLOCK)
ON dbo.Reports.type = dbo.Types.id
WHERE [dbo].[Reports].[Id] = @Id AND (row_num < (@page - 1) * 30) AND (row_num > @page * 30)
ORDER BY [dtd] DESC

1 个答案:

答案 0 :(得分:3)

您可以使用CTE

WITH CTE AS
(
   SELECT ROW_NUMBER() OVER(ORDER BY [dtd]) AS row_num, [data]
    FROM dbo.Reports INNER JOIN dbo.Types
    WITH (NOLOCK)
    ON dbo.Reports.type = dbo.Types.id
    WHERE [dbo].[Reports].[Id] = @Id 
)
SELECT * FROM CTE 
WHERE (row_num < (@page - 1) * 30) AND (row_num > @page * 30)
ORDER BY [dtd] DESC