简体   繁体   中英

Select middle rows in sql

I have a table in my SQLServer database with almost 100K records in it and a web application in which I want to show a paged gridView presentation of these rows. Clearly I should filter the rows and return a small subset of them to client(because of the Ajax performance on web).

Here's my main problem. What's the best approach to select the middle rows? For example How can I select the rows from #50000 to #50010? Is there a way like select top 10 or select bottom 10 that selects the rows from middle of the table rows.

I'm using linq2sql in a .NET MVC web application & also can code SQL StoredProcedures.

Any suggestion will be appreciated.

Not sure abt this, but anyway

SELECT *
FROM (SELECT ROW_NUMBER() OVER(ORDER BY colm) RowNumr, colm FROM table) t
WHERE RowNumr BETWEEN 50000 AND 50010

In Linq2Sql this is not that hard. You can use:

dataContext.GetTable()
    .Skip(50000)
    .Take(10)
    .ToList();

Scott Guthrie has a post on this matter, which has some more explanation. And Linq2Sql will actually produce sql using ROW_NUMBER() .

Some small hint, the order of your expressions is important:

  • .Where()
  • .Select()
  • .OrderBy()
  • .Skip()
  • .Take()

http://msdn.microsoft.com/en-us/library/ms186734.aspx

Check this link out, you can use the rownumber to get the rows you need based on a sort order. Just add a where clause where the rownumber is between the your paging limits.

Try this:

select * 
from(select table_name.*,rownum as rn from table_name order by column desc) table_name
where rn between 5000 and 5010;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM