限制SQL Server查询(用于分页)

时间:2012-10-04 22:10:02

标签: sql-server-2008 pagination limit

我有一个大型查询,可根据搜索情况撤回联系人。这是查询的简化示例。 (已更改表和字段名称以保护无辜者。)

SELECT DISTINCT TOP 20 DB1.FieldID, DB1.Field1, DB.Field2, DB.Field3,
DB2.Field88, DB3.Field77
FROM tblLamp DB1
LEFT JOIN tblSand DB2 ON DB2.FieldID = DB1.FieldID
LEFT JOIN tblLime DB3 ON DB3.FieldID = DB1.FieldID
WHERE (Field1 LIKE 'hotwet%' ESCAPE '!' OR Field2 LIKE 'maarten%' ESCAPE '!')
AND DB2.Field99 != '1111-2222-3333-4444'
AND (DB1.CreatorID IN (...) OR DB1.OwnerID IN (...) OR DB1.FieldID IN (...))
ORDER BY DB1.Field1 ASC, DB1.Field2 ASC

我在网上发现了很多使用ROW_NUMBER()的例子,但是我无法使用这个查询。有什么想法吗?

1 个答案:

答案 0 :(得分:0)

您可以将此小示例用作指南:

declare @test table(id int, name varchar(255));
insert into @test
  select 1, 'one' union
  select 2, 'two' union
  select 3, 'three' union
  select 4, 'four' union
  select 5, 'five' union
  select 6, 'six';

select
  *
from
(
  -- select the columns you need and include row number to enable limit 
  select
    name,
    row_number() over(order by id) as rownumber
  from
    @test
) v1
where
  rownumber between 2 and 4