IF WITHIN A SELECT

0
    SELECT  @VL_RET_INSS                = SUM(VL_RET_INSS),
            @VL_RET_IRRF                = SUM(VL_RET_IRRF),
      FROM  TABELA WHERE VALOR_TABELA > 0

I would like that when the value VL_RET_IRRF was less than 10 the field @VL_RET_IRRF would receive 0 and when it was greater than 10 received as I did today, could you help me? I do not know if I should use an if or how best, thank you.

    
asked by anonymous 12.03.2018 / 18:25

2 answers

3

You can use CASE WHEN

SELECT CASE WHEN @VL_RET_IRRF > 10 THEN 10 ELSE @VL_RET_IRRF END AS Result FROM Tabela

In the above SQL, it checks to see if the @VL_RET_IRRF is less than 10, if it is shown 10 otherwise it shows @VL_RET_IRRF

You can also use the IF command within SQL. Speaking of SQL Server, the newer versions from SQL Server 2012 have the IIF function which is an abbreviation of the IF ELSE function. Here's an example;

SELECT IIF(@VL_RET_IRRF > 10,10,@VL_RET_IRRF) AS Result FROM Tabela

To better understand the IIF function:

IIF(Expressão de comparação, resultado se for verdadeiro, resultado se for falso)
    
12.03.2018 / 18:29
2

Simple:

SELECT 
CASE WHEN @VL_RET_IRRF > 10 THEN 10 ELSE @VL_RET_IRRF END AS Result 
FROM Tabela

Multiple:

SELECT 
(CASE WHEN @VL_RET_IRRF >= 10 THEN 10 ELSE 
(CASE WHEN @VL_RET_IRRF >= 20 THEN 20 ELSE 
(CASE WHEN @VL_RET_IRRF >= 30 THEN 30 ELSE @VL_RET_IRRF END) 
END) END) AS Result 
FROM Tabela

Documentation: Here

    
12.03.2018 / 18:37