CASE SQL Error Statement

In C #, we can write

switch(num)
{
  case 0:
  case 1: // do something; break;
  case 2:
  ............
  ...........
  case n: // do something break;
  default: //do something; break;
}

      

How can I get stuff like this in SQL SERVER?

I am not talking about the easy way to write CASE in SQL SERVER. I am talking about whether I need to do the same operation king in 2 or more cases like what I showed in the C # code snippet how to do similar things in SQL CASE?

EDIT:

Now I have good answers. How to convert the following

SELECT CASE 
         WHEN [A]= num THEN '-' ELSE '' END [A], 
         CASE WHEN [B]= num THEN '-' ELSE '' END [B], 
         CASE WHEN [C]= num THEN '-' ELSE '' END [C],
         CASE WHEN [D]= num THEN '-' ELSE '' END [D]

      

... into something like:

SELECT CASE WHEN [A], 
       CASE WHEN [B], 
       CASE WHEN [C], 
       CASE WHEN [D] = num THEN '-' ELSE '' END [A] or [B] or [C] or [D]

      

I actually need this in the PIVOT request. I solved the problem last night. But I am not sure about this letter. Because every time I do the same. So is there a better way to represent this?

+2


source to share


4 answers


You may be looking for this.

SELECT
      CASE 
         WHEN (num BETWEEN 0 AND 2) THEN 'Between 0 and 2'
         WHEN (num = 3) THEN '3'
         ELSE 'Something else'
      END
...

      



More information on CASE from MSDN.

+4


source


SQL supports operator CASE

, but it is not the same as operator switch

in high level languages ​​like C # and Java. In a switch statement, you have the concept of failure, where if no statement break

is encountered, the flow continues until the next one CASE

. In contrast, the SQL statement CASE

behaves like a high-level language if(value==1){ ... }else if(value==2){ ... }else{ ... }

.



+2


source


Like C # SWITCH statement, SQL Server CASE expression does not support failure.

Note the emphasis on expression - it shouldn't be used for flow control, use the specified here .

+2


source


Like this:

SELECT 
  CASE num
    WHEN 0 THEN ...
    WHEN 1 THEN ...
    ELSE ...
  END as SomeCol
FROM ...

      

+1


source







All Articles