Convert negative data into positive data in SQL Server

SqlSql Server

Sql Problem Overview


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.

Sql Solutions


Solution 1 - Sql

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

Solution 2 - Sql

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

Solution 3 - Sql

UPDATE mytbl
SET a = ABS(a)
where a < 0

Solution 4 - Sql

Use the absolute value function ABS. The syntax is

ABS ( numeric_expression )

Solution 5 - Sql

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionWhat&#39;sUPView Question on Stackoverflow
Solution 1 - SqlLamakView Answer on Stackoverflow
Solution 2 - SqlAbdul SaboorView Answer on Stackoverflow
Solution 3 - SqlSam DeHaanView Answer on Stackoverflow
Solution 4 - SqlAdam PoradView Answer on Stackoverflow
Solution 5 - Sqlruddy simonpourView Answer on Stackoverflow