Hi is there a way to use decode to check for positive and negative values in sql?
e.g.
select decode(money_return, **<0**, abs(money_return), **>0**,
money_return*10, money_return) from cash_t;
if the logic is coded in if else statement it will be something like this:
if(money_return<0){money_reutrn = abs(money_return);}
else if(money_return>0){money_reutrn = money_return*10;}
else {money_return = money_return;}
end
Thank you.
In SQL Server, the T-SQL SIGN() function returns the sign of a number. In other words, it indicates whether or not the value is a positive number, a negative number, or zero. You provide the number as an argument when calling the function.
DECODE compares the expression to each search value one by one. If expression is equal to a search, then the corresponding result is returned by the Oracle Database. If a match is not found, then default is returned. If default is omitted, then Oracle returns null.
DECODE compares expr to each search value one by one. If expr is equal to a search , then Oracle Database returns the corresponding result . If no match is found, then Oracle returns default . If default is omitted, then Oracle returns null.
The basic syntax for writing DECODE function in SQL is as follows: DECODE (expression , search_1, result_1[, search_2, result_2], ...,[,search_n,result_n] [, default]); The parameters used in the above mentioned syntax are: expression: expression argument is the value which is to be searched and compared with.
You can use 'sign' with a decode. Sign will return -1 for any negative, 0 for 0, and 1 for any positive:
select decode(sign(money_return), -1, abs(money_return),
1, money_return*10,
money_return)
from cash_t;
You need case statement
select CASE
WHEN money_return < 0 THEN abs(money_return)
WHEN money_return > 0 THEN money_return*10
ELSE money_return END money_return from cash_t;
Use SIGN(). It returns "0" for 0, "1" for positive and "-1" for negative values.
SELECT
DECODE(
SIGN(money_return),
0,
money_return,
1,
money_return * 10,
- 1,
ABS(money_return)
)
FROM
CASH_T;
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