SQL Tip #4 – Pagination

Presenting a small subset of relevant information to the user at a time is very important. This type of small presentation of data is very important, otherwise user will be overwhelmed with a lot of information in front of them, and also by fetching all the information in one go will create pressure on the application  and as well as on the underlying database. As a result the end user will ended with the negative experience.

With the help of pagination, contents can be divided into different pages, and then retrieval of any given pages can be achieved efficiently with optimal performance.

In order to implement pagination, one of the following stored procedures could be used:

SQL 1:

	CREATE PROC [dbo].[proc_Employee_Select]
	(
		@pageNo int,
		@pageSize int
	)
	AS
	BEGIN

	DECLARE @StartPosition INT
	DECLARE @EndPosition INT

	SET @StartPosition = ((@pageNo - 1) * @pageSize )+ 1
	SET @EndPosition = @pageNo*@pageSize 

		SELECT EmployeeId,EmployeeName,Salary FROM
		(
			SELECT ROW_NUMBER()
			       OVER( ORDER BY  EmployeeId) AS Rid, *
			       FROM Employee 

		) Wrapper

		WHERE Wrapper.Rid BETWEEN @StartPosition AND @EndPosition
	END

SQL 2:

	CREATE PROC [dbo].[proc_Employee_Select_2nd]
	(
		@pageNo int,
		@pageSize int
	)
	AS
	BEGIN

		DECLARE @StartPosition INT
		DECLARE @EndPosition INT

		SET @StartPosition = ((@pageNo - 1) * @pageSize )+ 1

		DECLARE @EmpId INT
		SELECT TOP (@StartPosition) @EmpId = EmployeeId FROM Employee

		SELECT TOP (@pageSize) * FROM Employee
		WHERE EmployeeId>=@EmpId
		ORDER BY EmployeeId

	END

SQL 3:

	CREATE PROC [dbo].[proc_Employee_Select_3rd]
	(
		@pageNo int,
		@pageSize int
	)
	AS
	BEGIN
		
		DECLARE @StartPosition INT
		DECLARE @EndPosition INT
		
		SET @StartPosition = ((@pageNo - 1) * @pageSize )+ 1


		DECLARE @EmpId INT
		SET ROWCOUNT @StartPosition
		SELECT @EmpId = EmployeeId FROM Employee
		
		SET ROWCOUNT @pageSize
		SELECT * FROM Employee
		WHERE EmployeeId>=@EmpId
		ORDER BY EmployeeId
		SET ROWCOUNT 0

	END
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s