68

The current data of the table is:

  a   b
---------
 -1   5
-11   2
 -5  32

My request is to convert every data into a positive value.

Unfortunately, I forgot the name of the built-in function of SQL Server that enables to convert.

1
  • 2
    Don't mind them. Good question and good answers provided!
    – John Mc
    Feb 15, 2013 at 11:04

6 Answers 6

134

You are thinking in the function ABS, that gives you the absolute value of numeric data.

SELECT ABS(a) AS AbsoluteA, ABS(b) AS AbsoluteB
FROM YourTable
29

The best solution is: from positive to negative or from negative to positive

For negative:

SELECT ABS(a) * -1 AS AbsoluteA, ABS(b) * -1 AS AbsoluteB
FROM YourTable

For positive:

SELECT ABS(a) AS AbsoluteA, ABS(b)  AS AbsoluteB
FROM YourTable
2
  • 1
    The best solutions come from reading the question carefully. The OP wanted everything +ve not everything inverted.
    – Jamiec
    Apr 18, 2013 at 10:50
  • 1
    Agree but i came here to find the positive to negative, and this solution came into my mind and i posted it. and if you notice i mentioned in answer positive to negative and negative to positive. May be helpful for some one else. Apr 18, 2013 at 13:32
10
UPDATE mytbl
SET a = ABS(a)
where a < 0
8

Use the absolute value function ABS. The syntax is

ABS ( numeric_expression )
3

An easy and straightforward solution using the CASE function:

SELECT CASE WHEN ( a > 0 ) THEN (a*-1) ELSE (a*-1) END AS NegativeA,
       CASE WHEN ( b > 0 ) THEN (b*-1) ELSE (b*-1) END AS PositiveB
FROM YourTableName
1

Update all negatives to positive

UPDATE my_table 
SET value = ABS(value)
WHERE value < 0 

Get all the negative

SELECT value FROM my_table 
WHERE value < 0 

Get all the negatives and convert them to positive

SELECT ABS(value) FROM my_table 
WHERE value < 0 
1
  • What does this answer add to the question? The update is already shown here, and the select here
    – Shmiel
    Jul 3, 2022 at 19:16

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.