Saturday, October 25, 2008

Procedure for custom paging in SQL Server 2005

Hi,

Today, i was getting data of more than 10 lakh records from mah database & filling up a grid of 10 records, but it was taking immense time so, i wrote a procedure that returns custom paging for a grid......Njoy the code....if ne queries, reply me :)

alter PROCEDURE sp_PagedItems
(
@Page int,
@RecsPerPage int
)
AS

-- We don't want to return the # of rows inserted
-- into our temporary table, so turn NOCOUNT ON
SET NOCOUNT ON


--Create a temporary table
CREATE TABLE #TempItems
(
ID INT IDENTITY,
CARID int,

title varchar(500)

)


-- Insert the rows from tblItems into the temp. table
INSERT INTO #TempItems (carid, title)
SELECT carid, title FROM carregister

-- Find out the first and last record we want
DECLARE @FirstRec int, @LastRec int
SELECT @FirstRec = (@Page - 1) * @RecsPerPage
SELECT @LastRec = (@Page * @RecsPerPage + 1)

-- Now, return the set of paged records, plus, an indiciation of we
-- have more records or not!
SELECT *,
MoreRecords =
(
SELECT COUNT(*)
FROM #TempItems TI
WHERE TI.ID >= @LastRec
)
FROM #TempItems
WHERE ID > @FirstRec AND ID < @LastRec


-- Turn NOCOUNT back OFF
SET NOCOUNT OFF



Cheers!!!

Ujjwal B Soni

No comments: