paging and sql server, using Row_Number()

Posted by gondar | Filed under ,

imagine you need to select only some data from a table, where that data, when is ordered by some field, probably the id, if is sequential, wont be as you would like to select the rows beetween position 5 and 15, for example, so in this cases we need to use Paging, one options is this i'll show:

declare @temp table (field1 datetime,field2 nvarchar(10))

declare @start int,

@end int

select @start=1,@end=20

while @start<=@end

begin

insert into @temp values (getdate()+@start,'Line '+cast(day(getdate()+@start)+@end as nvarchar(5)))

select @start=@start+1

end

select * from (

select *, row_number() over(order by field1) as 'Id' from @temp

)as tab

where Id between 5 and 15

hope it helps :)