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
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.
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.
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.
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.
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
...
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With