Let's Create a table which has your columns
CREATE TABLE T(
Val VARCHAR(45),
Seq INT,
Sequence INT
);
INSERT INTO T VALUES
('A', 1, 2),
('C', 2, 1),
('B', 3, 3);
Now, let's look to your code and then brings the conditions:
Here is your code:
ORDER BY
CASE
WHEN @T='ABC' Then Val,Seq
ELSE Sequence END
- If
@T = 'ABC
then order by Val
and Seq
AND DO NOT order by Sequence
.
- If
@T <> 'ABC'
then order Only with Sequence
.
If you run this query:
--You was trying--
DECLARE @T VARCHAR(3) = 'ABC'; --wil works only when @T <> ABC
SELECT *
FROM T
ORDER BY CASE WHEN @T='ABC' THEN Seq END, --Take INT
CASE WHEN @T='ABC' THEN Val --Take Varchar
ELSE Sequence -- Take INT
END;
It will throw the following error if @T = 'ABC'
Msg 245 Level 16 State 1 Line 5
Conversion failed when converting the varchar value 'A' to data type int.
same as you get
Conversion failed when converting the nvarchar value 'EX-02-60' to data type int.
Now, here is what you want according to the conditions you provide:
--Fixes--
DECLARE @T VARCHAR(3) = '1'; --Try to change it to ABC too
SELECT *
FROM T
ORDER BY CASE WHEN @T='ABC' THEN Val END, --Take varchar
CASE WHEN @T='ABC' THEN Seq -- Take INT
ELSE Sequence -- Take INT
END;
/*
IF @T = ABC
ORDER BY Val, Seq; NOT Sequence
IF @T <> ABC
ORDER BY ONLY Sequence
*/
And here is a Live demo