Reputation: 12829
Why doesn't this work?
DECLARE @temp table
(ShipNo int,
Supplier varchar(10)
)
INSERT INTO @temp VALUES (1,'CFA')
INSERT INTO @temp VALUES (1, 'TFA')
INSERT INTO @temp VALUES (2, 'LRA')
INSERT INTO @temp VALUES (2, 'LRB')
INSERT INTO @temp VALUES (3, 'ABC')
INSERT INTO @temp VALUES (4, 'TFA')
Declare @OrderBy varchar(255)
sET @OrderBy = 'Supplier'
SELECT ROW_NUMBER() OVER (ORDER BY
CASE @OrderBy
WHEN 'Supplier' THEN Supplier
WHEN 'ShipNo' THEN ShipNo
END
) AS RowNo,
ShipNo,
Supplier
FROM @temp
But if you cast the ShipNo to a varchar in the Case statement it DOES work?
Upvotes: 0
Views: 14716
Reputation: 56
I am aware that this is old post but this is for any one who tumbles upon this issue and is looking for a solution:
SELECT ROW_NUMBER() OVER (ORDER BY
CASE @OrderBy
WHEN 'Supplier' THEN Supplier
END
CASE @OrderBy
WHEN 'ShipNo' THEN ShipNo
END
)
basically you are putting each field in its own case. Do this only when their data type or value inside field differs for both the columns or when you are getting error such as
conversion failed when trying to convert int to varchar or varchar to int..
Upvotes: 4
Reputation: 37192
From Books Online:
CASE
WHEN Boolean_expression THEN result_expression
[ ...n ]
[
ELSE else_result_expression
]
END
"The data types of else_result_expression and any result_expression must be the same or must be an implicit conversion."
So Supplier and ShipNo must be the same datatype.
Upvotes: 1