I was working on a website and needed a way to display my log information in a gridview control but allow paging through a certain number of articles at a time so that if the user was viewing the complete archive, the page wouldn't be too long.
The default paging in the ASP.NET gridview control does not scale well as it always retrieves all the records from the database and then only displays the ones you want. I wanted to rather fetch only the records that I needed for the current page and let SQL so all the work so that the impact on my web application was less.
After some searching on the web I found various articles but nothing that really worked for me so I decided to write my own. Incidentally, I started by drawing the logic out on a piece of paper before just diving into the code and this really helped with my focus and made sure that I didn't waste time going in the wrong direction. Now, let's get to the code...
Firstly, the structure of my SQL News Article table is as follows:
The logID is an auto-incrementing identity column .
So in addition to the paging, I needed to be able to filter my records by logTable/logOper/logTime as well as search word(s) found in the Title or Body fields. To do this, I created a stored procedure that looks like this:
IF OBJECT_ID (N'sp_GetLogs',N'P') IS NOT NULL
DROP PROC sp_GetLogs
go
CREATE PROC sp_GetLogs
@iPageIndex INT,
@iMaxRows INT,
@search varchar(1000)
AS
BEGIN
SET NOCOUNT ON;
DECLARE @iStart INT
SELECT @iStart = (@iPageIndex - 1) * @iMaxRows
DECLARE @iEnd INT
SELECT @iEnd = @iStart + @iMaxRows
IF OBJECT_ID (N'#TempLogs',N'U') IS NOT NULL
DROP TABLE #TempLogs
CREATE TABLE #TempLogs(
intUniqueID INT PRIMARY KEY IDENTITY(1, 1),
userCName NVARCHAR(100),
logTable VARCHAR(50),
logOper VARCHAR (50),
logTime VARCHAR(50),
logContent NVARCHAR(300))
DECLARE @SQLSTR VARCHAR(1000)
SET @SQLSTR='INSERT #TempLogs SELECT U.userCName,S.logTable,S.logOper,S.logTime,S.logContent
FROM Sys_Log S
INNER JOIN JC_Userinfo U ON U.userID = S.logUser
WHERE '+@search;
PRINT(@SQLSTR)
EXEC (@SQLSTR)
SELECT * FROM #TempLogs
WHERE intUniqueID > @iStart
AND intUniqueID <= @iEnd
END
GO
EXEC sp_GetLogs 2,5,'LOGTABLE=''JC_DEPARTMENT'''