paging stored procedure

use BalloonShop
select * from Product


-- 20 characters, 1, 5 
CREATE  PROCEDURE GetProductsOnCatalogPromotion
( @DescriptionLength  INT , --Description length @PageNumber INT , --Number of pages @ProductsPerPage INT , --How many products are displayed on each page @HowManyProducts INT OUTPUT --How many products are there in total )
 AS -- declare a new TABLE variable DECLARE @Products TABLE --table variable 
(RowNumber INT , --Add a reliable number field 
 ProductID INT to the original product table ,
 
 
 


   
 Name VARCHAR(50),
 Description VARCHAR(5000),
 Price MONEY,
 Image1FileName VARCHAR(50),
 Image2FileName VARCHAR(50),
 OnDepartmentPromotion BIT,
 OnCatalogPromotion BIT)

-- populate the table variable with the complete list of products
INSERT INTO @Products
SELECT ROW_NUMBER() OVER (ORDER BY Product.ProductID),
       ProductID, Name,
       SUBSTRING(Description, 1, @DescriptionLength) + '...' AS Description,
       Price, Image1FileName, Image2FileName, OnDepartmentPromotion, OnCatalogPromotion
FROM Product
WHERE OnCatalogPromotion = 1

--Assign the output parameter @HowManyProducts 
SELECT  @HowManyProducts  =  COUNT (ProductID) FROM  @Products

-- extract the requested page of products 
-- Query the content of the requested page from the @Products table variable 
SELECT ProductID, Name, Description, Price, Image1FileName,
       Image2FileName, OnDepartmentPromotion, OnCatalogPromotion
FROM @Products
WHERE RowNumber > (@PageNumber - 1) * @ProductsPerPage
  AND RowNumber <= @PageNumber * @ProductsPerPage
GO

use BalloonShop

--Understanding table variables 
DECLARE  @Products  TABLE 
(RowNumber INT ,
 ProductID INT,
 Name VARCHAR(50),
 Description VARCHAR(5000),
 Price MONEY,
 Image1FileName VARCHAR(50),
 Image2FileName VARCHAR(50),
 OnDepartmentPromotion BIT,
 OnCatalogPromotion BIT)
INSERT INTO @Products    
SELECT  Row_number() OVER (ORDER BY ProductID) , * from Product where OnCatalogPromotion = 1

select * from @Products
go

use BalloonShop
declare @HowManyProducts int
exec GetProductsOnCatalogPromotion 15,2,6, @HowManyProducts out 
select @HowManyProducts

-- How many pages in total: total number of products / number of products per page (decimal) = 2.1 
-- ceiling

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325019077&siteId=291194637