Fyi - mssql select top 10 next 10 (fwd)

-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

This is a follow up on the sybase/mssql support question I asked a few
weeks ago. Below is an example of how to get a limit/offset query
working in mssql using sub-selects.

But then we may have convinced our DB As that PgSQL will probably meet
our enterprise needs, so for now we’re not pushing for this support.

Joby Walker
ITI SSG, University of Washington


PGP key: https://staff.washington.edu/joby/joby-u-pub.asc

http://www.planet-source-code.com/vb/scripts/ShowCode.asp?txtCodeId=850&lngWId=5

stumbled on this when looking for something else – request tracker
question a couple weeks ago –

The following query will emulate a

SELECT emp_id,lname,fname FROM employee LIMIT 20,10

That says, give me 10 records starting at record 21. So what will be
returned are rows 21-30. This is used heavily in web-based apps so you can
do recordset paging.

Here is what you can do in MS SQL to emulate it (this runs on the PUBS
db):

select * from (
select top 10 emp_id,lname,fname from (
select top 30 emp_id,lname,fname
from employee
order by lname asc
) as newtbl order by lname desc
) as newtbl2 order by lname asc

The main thing to remember is to deal with all your ORDER BY clauses and
also to use the inner TOP as the sum of what you are looking for. In this
example - 30 since you start at 20 and want 10 rows (20+10=30).

Hope this helps you as it has helped me improve performance greatly on my
web-based apps since I no longer have to transfer loads of data across the
wire to get just the 10 results I display on a page.

Don’t even think about using the internal ADO paging stuff if you have a
lot of records to deal with, it will kill your performance as it must pull
the entire recordset down to the local machine before it can do its work.
Why bring down 20,000 records if you only want to display 10?

Enjoy!

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.1 (GNU/Linux)
Comment: Using GnuPG with Thunderbird - http://enigmail.mozdev.org

iD8DBQFCszVngA0gpghkf88RAhpKAKDBRJrl2jV6awLXMY6EX6AFxJoTgACgiQRG
lbmbBnVyks75CR9vmddaJZg=
=5ssB
-----END PGP SIGNATURE-----