Dynamic Sorting with Pagination - SQL Server - cSharp Coder

Latest

cSharp Coder

Sharp Future

Friday, May 28, 2021

Dynamic Sorting with Pagination - SQL Server

 

Preparing Sample Data

Before beginning to go into detail about the pagination, we will create a sample table and will populate it with some synthetic data. In the following query, we will create a SampleFruits table that stores fruit names and selling prices. In the next part of the article, we will use this table.

Sample table for paging in SQL


Dynamic Sorting with Pagination

Applications may need to sort the data according to different columns either in ascending or descending order beside pagination. To overcome this type of requirement, we can use an ORDER BY clause with CASE conditions so that we obtain a query that can be sorted by the variables. The following query can be an example of this usage type:

Dynamic sorting with pagination

Also, we can change the sort column and sorting direction through the variables for the above query.

Pagination in a Loop

In this example, we will learn a query technique that returns all discrete page results with a single query.

What is pagination in SQL Server

For this query, we created a pretty simple formula. At first, we assigned the total row number of the SampleFruit table to the @MaxTablePage variable, and then we divided it into how many rows will be displayed on a page. So, we have calculated the number of pages that will be displayed. However, the calculated value can be a decimal, and for that, we used the CEILING function to round it up to the smallest integer number that is bigger than the calculated number. As a second step, we implemented a WHILE-LOOP and iterated @PageNumber variable until the last page of the number.

No comments:

Post a Comment