简体   繁体   中英

How to implement paging of rows with WCF and SQL Server?

Firstly, I am a newbie to WCF and SQL Server. I am developing an application that connects with WCF and SQL Server 2012. I have a table with rows having a million records and that count will keep on increasing. When the client sends a request, I will fetch 30 rows and then show the next 30 rows if the user request it and so on. My requirement is to do paging in WCF or in SQL. I have the following questions:

  1. I was wondering where should I implement the paging concept, in WCF or in SQL Server? Which approach is the fastest?
  2. If I implement it in WCF I will use LINQ's Skip and Take operators to fetch the page requested. Is that the right way?
  3. If I use SQL, which approach will fetch the fastest result OFFSET (or) ROW_NUMBER() OVER option?

Since I am new, these approaches are what I know. Is there any other approach that I don't know of?

  1. You want to page on SQL Server, if you don't every query you make will return a million rows you must load in to memory then you immediately throw away all but 30 of them. Very inefficient.
  2. It depends on what you mean. If you are using something like Entity Framework using Skip and Take will not do those operations in memory, it will transform them in to sql queries and run them in sql.
  3. If it is available to you OFFSET will give you better performance than ROW_NUMBER() OVER .

One thing to note, if you are doing paging you must make sure your ordering is deterministic. There can be no ties in ordering, if you allow ties you could have one right on your page break. Lets say Row A and Row B are "tied" by your order by:

  • You run a query for page 1 and Row A is considered to be before Row B and Row A is shown as the last item on the page
  • You run a query for page 2 and Row B is considered to be before Row A and Row A is shown as the first item on the 2nd page.

You never displayed Row B in the above example. The easiest way to fix this is always make sure you do a order by on your primary key (or any other set of columns you could do a unique index on) as the last thing you order by, this makes sure you never have any ties.

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