Tuesday, April 28, 2009

MySQL Limit - how to simulate with Microsoft SQL Server 2005

Much less strategic that previous post, I am quicly cooking a primitive web interface for which I need pagination.

In MySQL the limit added to the select helps verymuch retrieving a block of rows then the next one for the next page etc

What about MS Sqlserver ? You may start with TOP (takes the first rows) or set rowlimit.

But how to start at a given row ?

I found a few desperately incorrect proposals for this (but at least one pointed me to the ranking functions) , here is my best shot:

"with ordtab as (select p_users_id , ROW_NUMBER() OVER (order by p_users_id) as rownumber from ph_users) select * from ordtab where rownumber >= 10 and rownumber <= 20"

Will give you the equivalement of limit 10,20.

The solution is based on what is in the Microsoft manual, too bad we don't have time to read that much manuals, however it is still much less elegant than the MySQL attribute (which is right to the point)...

No comments: