You need to know an important note about the CASE
statement in T-SQL:
The CASE expression evaluates its conditions sequentially and stops with the first condition whose condition is satisfied
Read more here:https://learn.microsoft.com/en-us/sql/t-sql/language-elements/case-transact-sql?view=sql-server-2017
So, based on the aforementioned tip, you CASE
will not be executed as you expected, because if we assume that your first condition(a>b) is true, then the evaluation of CASE
will be stopped and you will not get the other conditions results.
To solve it you need to write a CASE
statement for each your conditions as below:
SELECT *,
CASE WHEN a > b THEN b ELSE a END AS AorB,
CASE WHEN c > d THEN d ELSE c END AS CorD,
CASE WHEN e > f THEN f ELSE e END AS EorF,
CASE WHEN g > h THEN h ELSE g END AS GorH,
CASE WHEN i > j THEN j ELSE i END AS JorI,
CASE WHEN k > l THEN l ELSE k END AS LorK,
CASE WHEN m > n THEN n ELSE m END AS MorN,
CASE WHEN o > p THEN p ELSE o END AS OorP
INTO #temptable
From #atemptable
Update
As you mentioned in your comment:
I am trying to evaluate an expression where it is checking if one variable is greater than the other. if it is then set the lesser variable equal to the greater variable
So the story as totally different and you should use an approach like this:
Suppose that we have a set of variables which are defined as below:Read more about Variable definition in T-SQL: https://learn.microsoft.com/en-us/sql/t-sql/language-elements/declare-local-variable-transact-sql?view=sql-server-2017
DECLARE
@a INT = 2, @b INT = 1,
@c INT = 3, @d INT = 4,
@e INT = 6, @f INT = 5,
@g INT = 7, @h INT = 8,
@i INT = 10,@j INT = 9,
@k INT = 12,@l INT = 11,
@m INT = 13,@n INT = 14,
@o INT = 16,@p INT = 15
To evaluate your scenario we need to write the code as below:
SET @b= CASE WHEN @a > @b THEN @a ELSE @b END
SET @d= CASE WHEN @c > @d THEN @c ELSE @d END
SET @f= CASE WHEN @e > @f THEN @e ELSE @f END
SET @h= CASE WHEN @g > @h THEN @g ELSE @g END
SET @j= CASE WHEN @i > @j THEN @i ELSE @i END
SET @l= CASE WHEN @k > @l THEN @k ELSE @k END
SET @n= CASE WHEN @m > @n THEN @m ELSE @m END
SET @p= CASE WHEN @o > @p THEN @o ELSE @o END
So if we execute the SELECT, we will see the result:
SELECT @a,@b, ...