Use IF function in SQL as if excel [closed]

closed . This question needs details or to be clearer and is not currently accepting answers.

want to improve this question? Add details and make it clearer what problem is being solved by editing this post .

Closed 2 years ago .

improve this question

Exists in SQL a function equivalent to IF (SE) excel? I need to do a logical test that in excel I would write like this =SE(B1_UM = "UN"; D2_QUANT / B5_QE1;D2_QUANT).

Here is my query:

SELECT
   D2_FILIAL,
   // Um monte de coluna...
   CASE
      B1_UM 
      WHEN
         'UN' 
      THEN
         D2_QUANT / B5_QE1 
      ELSE
         D2_QUANT 
   END AS CALC_QUANT 
FROM
   SD2010 SD2 
   // Vários joins
WHERE com várias condições
GROUP BY
   D2_FILIAL, 
   // Várias outras colunas no group
   CALC_QUANT
Author: Mhac, 2018-05-16

2 answers

To handle conditional results in sql-server you have basically three structures:

1. IIF (bolean expression, value if true, value if false )

Example:

SELECT IIF(id = 1, 'VERDADEIRO', 'FALSO') as Expressao
FROM tabela

2. CASE expression when value 1 THEN Result 1 (...) END

Example:

SELECT CASE id 
           WHEN 1 THEN 'ID é 1'
           WHEN 2 THEN 'ID é 2'
           ELSE 'ID é outra coisa'
       END as Expressao
FROM tabela

3. Case when bolean expression THEN Result (...) END

Example:

SELECT CASE  
           WHEN id = 1 THEN 'ID é 1'
           WHEN id > 5 THEN 'ID é maior que cinco'
           ELSE 'Não sei o que fazer com o ID'
       END as Expressao
FROM tabela

I hope this has cleared up your doubts.

 0
Author: Diego Rafael Souza, 2018-05-16 19:01:22

What are you looking for I believe this is

select iif(sexo = 0, 'Feminino', 'masculino') from clientes

Edited

Fix the command above

As quoted in this link , the IIF command(condition, resppositive, respnegative) should work if your SQL SERVER is 2012 +

 -1
Author: Matheus Ribeiro, 2018-05-16 18:55:43