I have the following SQL:
ALTER PROCEDURE [dbo].[SP_Products_GetList]
@CatID int,
@CatName int,
@SortBy varchar(50),
@SortType varchar(50)
AS
SELECT Products.ProductID, ProductName, MAX(Price) Price FROM Products
INNER JOIN ProductCategory
on Products.ProductID = ProductCategory.ProductID
INNER JOIN (
SELECT * FROM Categories
WHERE
( @CatID is null or @CatID = CatID ) and
( @CatName is null or @CatName = CatName )
) Categories
on ProductCategory.CatID = Categories.CatID
INNER JOIN (
SELECT ProductID, max(Price) Price from Prices WHERE PriceID IN
( SELECT MAX(PriceID) FROM Prices
GROUP BY ProductID , SizeID)
GROUP BY ProductID
) as Prices
on Prices.ProductID = Products.ProductID
GROUP BY ProductName, CatName, Products.ProductID, Price
ORDER BY
CASE @SortType
WHEN 'desc' THEN
CASE @SortBy
WHEN 'ProductID' THEN Products.ProductID
WHEN 'ProductName' THEN ProductName
WHEN 'Price' THEN Price
END
END
EXECUTION PASSS
EXEC [dbo].[SP_Products_GetList]
@CatID = 1,
@CatName = NULL,
@SortType = 'DESC',
@Sortby = 'ProductID'
EXECUTION FAILED
EXEC [dbo].[SP_Products_GetList]
@CatID = 1,
@CatName = NULL,
@SortType = 'DESC',
@Sortby = 'ProductName'
Msg 245, Level 16, State 1, Procedure SP_Products_GetList, Line 13 Conversion failed when converting the varchar value '01-My First Tools Diaper Cake' to data type int.
When I alter my query without case and write simple:
.....
ORDER BY ProductName
It works fine
Why is is trying convert varchar
to int
as shown in the error message?