Skip to content

Instantly share code, notes, and snippets.

@michaelhenry
Created May 20, 2013 16:22
Show Gist options
  • Save michaelhenry/5613365 to your computer and use it in GitHub Desktop.
Save michaelhenry/5613365 to your computer and use it in GitHub Desktop.
Just a mssql code that I wrote from my past :) It will create query paginator :)
DECLARE @PageIndex AS INT;
DECLARE @PageSize AS INT;
DECLARE @PagerSize INT;
SET @PagerSize = 10;
SET @PageIndex = 1222;
SET @PageSize = 10;
DECLARE @AllRow INT;
DECLARE @MaxPageIndex INT;
SELECT @AllRow = COUNT(PinID) FROM Pin;
IF @AllRow%@PageSize = 0
BEGIN
SET @MaxPageIndex = @AllRow/@PageSize ;
END
ELSE
BEGIN
SET @MaxPageIndex = (@AllRow/@PageSize) + 1;
END
SELECT @MaxPageIndex;
IF @PageIndex > 0 AND @PageIndex < @MaxPageIndex + 1
BEGIN
WITH tmpPin AS
(
SELECT ROW_NUMBER() OVER(ORDER BY PinID) AS RowID
,PinID
,ControlID
,SerialNo
,PinCode
FROM Pin
)
SELECT *
FROM tmpPin
WHERE RowID BETWEEN (@PageIndex - 1) * @PageSize + 1
AND @PageIndex * @PageSize
ORDER BY PinID ASC
END
DECLARE @PagerTable TABLE(PagerID INT)
--DECLARE @PagerSize INT;
-- SET @PagerSize = 11
--DECLARE @PageIndex INT;
-- SET @PageIndex = 11
DECLARE @InitialCurrentPageIndex INT
IF @PagerSize%2=0
BEGIN
SET @InitialCurrentPageIndex = @PageIndex - @PagerSize/2 + 1;
END
ELSE
BEGIN
SET @InitialCurrentPageIndex = @PageIndex - @PagerSize/2 ;
END
DECLARE @PagerIndex INT;
IF (@PageIndex > @PagerSize) AND (@PageIndex <= (@MaxPageIndex-@PagerSize))
BEGIN
SET @PagerIndex = @InitialCurrentPageIndex;
END
ELSE IF @PageIndex <= @PagerSize
BEGIN
SET @PagerIndex = 1;
END
ELSE IF (@PageIndex > (@MaxPageIndex-@PagerSize))
BEGIN
SET @PagerIndex = @MaxPageIndex-@PagerSize + 1;
END
SELECT @PagerIndex
DECLARE @PagerCounter INT;
SET @PagerCounter = 0;
WHILE @PagerCounter < @PagerSize
BEGIN
INSERT INTO @PagerTable(PagerID) VALUES(@PagerIndex);
SET @PagerIndex = @PagerIndex + 1;
SET @PagerCounter = @PagerCounter + 1;
END
SELECT * FROM @PagerTable;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment