我需要在网页上编写寻呼机的代码,通常使用mysql,它是SELECT with LIMIT 60, 20
的简单解决方案,这意味着从60个位置选择20行。
现在我正在使用SQL Server,但应该解决这个问题 - 我知道TOP语法不合适,我也听说过SQL Server中的ROW_NUMBER()
函数,但是我的例子d发现不够清楚 - 请帮助测试表像“汽车”一样简单地
select * from cars limit 20, 10
答案 0 :(得分:3)
ROW_NUMBER()不能在你的where子句中,所以你必须使用单独的select:
select *
from (select row_number() over (ORDER BY cars.CarId) as Row, *
from cars
) temp
where Row between 20 and 29
答案 1 :(得分:1)
SQL Server 2005引入了新的ROW_NUMBER()函数,使分页任务更容易。要实现与前面示例中的分页,请从Customers表中获取第三页,其中Country列为'Spain',每页有10条记录,并按CompanyName存储过程排序如下:
CREATE PROCEDURE Paging_Customers
(
@SelectedPage int,
@PageSize int
)
AS
BEGIN
WITH CTE_Customers(PageNumber, ContactTitle, ContactName, CompanyName, Phone, Country)
AS
(
SELECT CEILING((ROW_NUMBER() OVER
(ORDER BY CompanyName ASC
AS PageNumber, ContactTitle, ContactName, CompanyName, Phone, Country
FROM Customers
)
SELECT *
FROM CTE_Customers WHERE PageNumber = @SelectedPage
END
然后,我们用这个简单的行来调用这个过程(第三页和每行十行):
EXEC Paging_Customers 3, 10
答案 2 :(得分:0)
-- Sample data
;with cars(Name) as
(
select 'SAAB' union all
select 'Volvo' union all
select 'Opel' union all
select 'Ford'
)
-- Query using row_number
select *
from
(
select *,
row_number() over(order by Name) as rn
from cars
) as C
where C.rn between 2 and 3
结果:
Name rn
---- --
Opel 2
SAAB 3
答案 3 :(得分:0)
试试这个:
SELECT * FROM
(SELECT *, ROW_NUMBER() OVER (ORDER BY col1) AS row FROM sys.databases) table1
WHERE row > 20 and row <= 30
提供了更多答案here on SO。