Introduction
Sometimes while building an application (especially web-application) we need to have an opportunity to paginate through the data and to sort it. But we want the database to do all this stuff and we want to have one sproc that would return a part of data we need for the selected page and also this data should be sorted. I was trying to find related articles in the internet but most of them offered using dynamic queries. So I have built my own stored procedure.
Using the code
I have attached a file to this article contaning a sql script which demonstrates how we could create a sproc that would help to paginate and sort data.
As an example have used a table Employee, that has the following structure:
CREATE TABLE Employee
(
EmployeeID int IDENTITY(1, 1) PRIMARY KEY CLUSTERED,
FromDate datetime,
FirstName varchar(50),
LastName varchar(50),
EmailAddress varchar(255),
)
The procedure has the following parameters:
@OrderByField varchar(50) = NULL,
@OrderByAsc bit = 1,
@FirstRecordToDisplay int = NULL,
@NumberOfRecordsToDisplay int = NULL
The text of the procedure:
CREATE PROCEDURE usp_GetAllEmployees
@OrderByField varchar(50) = NULL,
@OrderByAsc bit = 1,
@FirstRecordToDisplay int = NULL,
@NumberOfRecordsToDisplay int = NULL
AS
SET NOCOUNT ON
DECLARE @TotalCount int
IF OBJECT_ID('tempdb..#tmpGetEmployee') IS NOT NULL DROP TABLE #tmpGetEmployee
CREATE TABLE #tmpGetEmployee
(
tmpGetID int IDENTITY(1, 1) PRIMARY KEY CLUSTERED,
EmployeeID int,
FromDate datetime,
FirstName varchar(50),
LastName varchar(50),
EmailAddress varchar(255)
)
INSERT #tmpGetEmployee(EmployeeID, FromDate, FirstName, LastName, EmailAddress)
SELECT EmployeeID, EmployeeFromDate, FirstName, LastName, EmailAddress
FROM [Employee]
ORDER BY
CASE WHEN @OrderByField = 'EmployeeID' THEN EmployeeID ELSE NULL END,
CASE WHEN @OrderByField = 'FromDate' THEN FromDate ELSE NULL END,
CASE WHEN @OrderByField = 'FirstName' THEN FirstName ELSE NULL END,
CASE WHEN @OrderByField = 'LastName' THEN LastName ELSE NULL END,
CASE WHEN @OrderByField = 'EmailAddress' THEN EmailAddress ELSE NULL END
SET @TotalCount = @@ROWCOUNT
DECLARE @k smallint
DECLARE @NewFirstRecord int
IF @OrderByAsc = 0
BEGIN
SET @k = -1
SET @NewFirstRecord = @TotalCount - ISNULL(@FirstRecordToDisplay, 1) + 1
END
ELSE
BEGIN
SET @k = 1
SET @NewFirstRecord = ISNULL(@FirstRecordToDisplay, 1)
END
SELECT
EmployeeID, FromDate, FirstName, LastName, EmailAddress
FROM #tmpGetEmployee
WHERE (@FirstRecordToDisplay IS NULL OR (tmpGetID - @NewFirstRecord) * @k >= 0 )
AND (@NumberOfRecordsToDisplay IS NULL OR (@NewFirstRecord + @k * @NumberOfRecordsToDisplay - tmpGetID) * @k > 0)
ORDER BY @k * tmpGetID
Good luck!
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.