我想知道你是否可以做这样的事情是Microsoft SQL Server 2k8 R2
假设我有一个返回100行数据的查询。
他们是否可以传递一些变量,例如@lower_limit和@upper_limit。
然后我希望查询记录下限和上限之间的行
例如:
@lower_limit = 5
@upper_limt 10
将从100条记录中返回5-10行。
答案 0 :(得分:6)
您可以在结果集上分配ROW_NUMBER(),然后使用BETWEEN
语句限制行。
一个人为的例子:
WITH data AS
(
SELECT
ID
,YourColumn
,ROW_NUMBER() OVER (ORDER BY ID) AS RowNum
FROM
YourTable
)
SELECT
*
FROM
data
WHERE
RowNum BETWEEN 5 AND 10
编辑:对于标准分页,这正是我在我开发的所有应用程序中使用的技术:
DECLARE @PageNumber int = /* The page number you want */
DECLARE @PageSize int = /* The number of records per page */
WITH paged AS
(
SELECT
ROW_NUMBER() OVER(ORDER BY [OrderByColumns]) AS RowNum
,*
FROM
[YourSource]
)
SELECT
[Column1]
,[Column2]
,...
FROM
paged
WHERE
RowNum BETWEEN (@PageNumber - 1) * @PageSize + 1 AND @PageNumber * @PageSize
ORDER BY
[OrderByColumns] -- Same as used in ROW_NUMBER()
答案 1 :(得分:0)
select *
from
(
select *, row_number() over(order by someColToOrderBy) RowNum
from yourTable
) a
where RowNum between @lower_limit and @uppder_limit
答案 2 :(得分:0)
这样的事情应该有效:
SELECT ID, Foo, Bar
FROM (
SELECT ROW_NUMBER() OVER (ORDER BY ID ASC) AS Row, ID, Foo, Bar
FROM SomeTable
)
tmp
WHERE Row >= @RowRangeStart AND Row <= @RowRangeEnd