I am trying to “Order by” my table by Id in Dynamic SQL, though it works with Name
and Description
(Both Type Nvarchar) as shown but not Working with Id
(type INT),
Here is my Dynamic SQL Query
';With data AS (Select P.Id, P.Name, P.Description, P.Price, 12 AS ActiveUsers, B.Name as BillingPeriod, CASE '+@SortField+' WHEN P.Name THEN ROW_NUMBER() OVER (ORDER BY P.Name) WHEN Description THEN ROW_NUMBER() OVER (ORDER BY P.Description) WHEN P.Id THEN ROW_NUMBER() OVER (ORDER BY P.Id) *****This Line Gives Error***** END rn ' --- REST of The SP ---
The Line Gives Following Error
Conversion failed when converting the nvarchar value ‘cereals’ to data type int.
I print SQL It shows …
CASE P.Id WHEN P.Name THEN ROW_NUMBER() OVER (ORDER BY P.Name) WHEN Description THEN ROW_NUMBER() OVER (ORDER BY P.Description) WHEN P.Id THEN ROW_NUMBER() OVER (ORDER BY P.Id) END rn From Products P
Please Help me with this, I am new to sql.
Advertisement
Answer
You could replace the entire CASE expression with …
';With data AS (Select P.Id, P.Name, P.Description, P.Price, 12 AS ActiveUsers, B.Name as BillingPeriod, ROW_NUMBER() OVER (ORDER BY '+@SortField+')' --- REST of The SP ---