Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IF, ELIF, ELSE in T-SQL

I am working in SQL Server 2008 and trying to use a IF, ELIF, ELSE statement in the SELECT section of my code. What I want to do is the following:

IF BO.VALUE < BO.REFERENCELOWERLIMIT
    THEN (BO.VALUE - BO.REFERENCELOWERLIMIT) #I WANT THIS TO BE NEGATIVE
ELSE IF BO.REFERENCELOWERLIMIT <= BO.VALUE <= BO.REFERENCEUPPERLIMIT
    THEN BO.VALUE
ELSE
    (BO.REFERENCEUPPERLIMIT - BO.VALUE)

The problem is that I do not understand how to do a IF, ELIF, ELSE type transaction in SQL. I have tried to search for this type of example and came across python examples...wrong language so I did a search on the MSDBN site and did not see this sort of work, just IF/ELSE.

Thank You

like image 339
MCP_infiltrator Avatar asked Mar 28 '13 14:03

MCP_infiltrator


People also ask

How do I use if else in SQL?

Any T-SQL statement can be executed conditionally using IF… ELSE. If the condition evaluates to True, then T-SQL statements followed by IF condition in SQL server will be executed. If the condition evaluates to False, then T-SQL statements followed by ELSE keyword will be executed.

Can you do if else statements in SQL?

The IF ELSE statement controls the flow of execution in SQL Server. It can be used in stored-procedures, functions, triggers, etc. to execute the SQL statements based on the specified conditions. Boolean_expression: A boolean expression that returns TRUE or FALSE.

Can you have multiple else statements in SQL?

You can use multiple else if but each of them must have opening and closing curly braces {} . You can replace if with switch statement which is simpler but only for comparing same variable.

Is != And <> the same in SQL?

If != and <> both are the same, which one should be used in SQL queries? Here is the answer – You can use either != or <> both in your queries as both technically same but I prefer to use <> as that is SQL-92 standard.


2 Answers

You want a CASE expression. CASE evaluates in order and the first match is what is returned in the query.

SELECT
  CASE WHEN BO.VALUE < BO.REFERENCELOWERLIMIT 
           THEN (BO.VALUE - BO.REFERENCELOWERLIMIT)
       WHEN BO.VALUE BETWEEN BO.REFERENCELOWERLIMIT AND BO.REFERENCEUPPERLIMIT
           THEN BO.VALUE
       ELSE  (BO.REFERENCEUPPERLIMIT - BO.VALUE)
  END as MyColumnAlias
...
like image 197
JNK Avatar answered Sep 18 '22 17:09

JNK


SELECT 
    col = CASE 
            WHEN BO.VALUE < BO.REFERENCELOWERLIMIT 
                THEN BO.VALUE - BO.REFERENCELOWERLIMIT
            WHEN BO.VALUE BETWEEN BO.REFERENCELOWERLIMIT AND BO.REFERENCEUPPERLIMIT 
                THEN BO.VALUE
            ELSE BO.REFERENCEUPPERLIMIT - BO.VALUE
FROM tbl
like image 31
T I Avatar answered Sep 19 '22 17:09

T I