select @RecordCount=count(1) from t_sharedfilesdoc; declare @lowRows int; declare @upRows int; set @lowRows = @startRowIndex; set @upRows = @lowRows + @maximumRows + 1; if @lowRows>@RecordCount begin set @lowRows=(@RecordCount/@maximumRows)*@maximumRows; if @lowRows=@RecordCount set @lowRows= @RecordCount-@maximumRows; end --select * from t_sharedfilesdoc select * from ( select ROW_NUMBER() OVER (ORDER BY docid desc) rownum,docid from t_sharedfilesdoc) as a where rownum>@lowRows and rownum<@upRows; select @RecordCount;