I am working on adding sorting functionality to an online store.
The query works fine when it has a hard coded ORDER BY, but not when the ORDER BY is a variable.
The query works fine when it has a hard coded ORDER BY, but not when the ORDER BY is a variable.
Code:
declare @CatID Int
declare @PageSize Int
declare @PageNumber Int
declare @OrderBy VarChar
declare @EntityName VarChar
set @CatID = 3158
set @PageSize = 10
set @PageNumber = 1
set @OrderBy = 'p.SalePrice'
set @EntityName = 'Category';
WITH ProductPaging AS (
SELECT
ROW_NUMBER() OVER ( ORDER BY @OrderBy ) AS RowNumber,
p.ProductID AS ProductID,
p.Name AS Name,
p.SKU AS SKU,
p.HidePriceUntilCart AS HidePrice,
pc.CategoryID AS CategoryID,
pc.DisplayOrder AS pcDisplayOrder,
p.Price AS Price,
p.SalePrice AS SalePrice
FROM
dbo.Product AS p INNER JOIN
dbo.ProductCategory AS pc ON p.ProductID = pc.ProductID
WHERE
(pc.CategoryID = @CatID) AND
(p.Published = 1) AND
(p.Deleted = 0)
)
SELECT *
FROM
ProductPaging
WHERE RowNumber BETWEEN (@PageSize*(@PageNumber-1))+1 AND (@PageSize * @PageNumber)
ORDER BY RowNumber
Comment