How can I make this correct? I am getting an error saying: Incorrect syntax near the keyword 'DESC'.
SELECT *
FROM Companies
Order By
CASE @OrderByField
WHEN 'CompanyName' THEN CompanyName
WHEN 'CreatedDate' THEN CreatedDate
END,
CASE @Direction
WHEN 'DESC' THEN DESC
WHEN 'ASC' THEN ASC
END
Can I not have two case statements? If not, how can i pass in the name of the order by field and direction as parameters?
Thanks!
Another problem surface after the first one is solved...
If I include a field that doesn't have the datatype of string, if throws an error. For example:
SELECT *
FROM Companies
Order By
CASE @Direction WHEN 'DESC' THEN
CASE @OrderByField
WHEN 'CompanyName' THEN CompanyName
WHEN 'CreatedDate' THEN CreatedDate
WHEN 'Score' THEN Score
END
END DESC,
CASE @Direction WHEN 'ASC' THEN
CASE @OrderByField
WHEN 'CompanyName' THEN CompanyName
WHEN 'CreatedDate' THEN CreatedDate
WHEN 'Score' THEN Score
END
END ASC
@OrderByField is type of nvarchar(50) assume Score has a datatype of float.
Above throws an error like the one below even if i am not trying to order by the score field. Error converting data type nvarchar to float.
Similarly, including a createddate throws an error: Conversion failed when converting date and/or time from character string.
Will be very appreciated if anyone can help out.
casepart of answer by gbn on second link; those seem to be exactly what you're after?