Monday, December 5, 2011

Paging in SQL Server (2008)

declare @customers table(custid int,cusname varchar(50))

insert into @customers(custid,cusname)
values(1,'C1'),(2,'C2'),(3,'C3'),(4,'C4'),(5,'C5'),(6,'C6'),(7,'C7'),(8,'C8'),(9,'C9'),(10,'C10')

declare
@PageSize int, @PageNumber int

set @PageSize = 5
--set @PageNumber = 1
set @PageNumber = 2

Declare @RowStart int
Declare @RowEnd int

if @PageNumber > 0
Begin

SET @PageNumber = @PageNumber -1

SET @RowStart = @PageSize * @PageNumber + 1
SET @RowEnd = @RowStart + @PageSize - 1

end

;with cust as
(
select custid, cusname, row_number() over (order by custid) RowNumber
from @customers
)
select custid, cusname from cust where RowNumber >= @RowStart and RowNumber <= @RowEnd

No comments:

Popular Posts