CASE conditions in Transact-SQL




Another way for using conditions in Transact-SQL besides IF…ELSE is CASE operator. The syntax is some different from IF…ELSE but in some cases more readable. CASE also uses the word "THEN".
declare @val INT;
select
   CASE
      WHEN @val = 0 THEN {action 1}
      WHEN @val > 0 THEN {action 2}
      ELSE {action 3}
   END as val

On a live example, it looks like this:

declare @val INT = -3 
select 
   CASE 
      WHEN @val = 0 THEN (SELECT pcname from computers where cid = (@val +1)) 
      WHEN @val > 0 THEN (SELECT Title from Book where ID = @val) 
      ELSE (SELECT ManagerName from managers where mid = ABS(@val)) 
   END as val

The results of this query:

If @val is less than zero, for example,  "-3", the result is "SELECT ManagerName from managers where mid = 3)"

If @val is equal to "0", the result is "SELECT pcname from computers where cid = 1"

If @val is greater than zero, for example, to "1", the result is "SELECT ManagerName from managers where mid = 1)"

 




No Comments »

No comments yet.

RSS feed for comments on this post. TrackBack URL

Leave a comment





MarkiMarta.com. Notes of web-specialist
Since 2009
18+