Convert positive to negative and vice versa

  • Is there a function within SQL to convert any negative values to positive and the positive ones to negative?

     

    Thanks

  • I don't know about a function but just multiply by -1.

     

    For example:

     

    update InvoiceDtl set UnitPrice = UnitPrice * -1

  • That'll work. ta

  • Actually if you only want ONLY positive values you'd be better off doing something like this :

    Select ABS(MyCol) from dbo.MyTable

  • I have used th case statement to do reverse the values present in the Table

    select

    case

    when MyCol>0 then 0-MyCol

    else

    abs(MyCol)

    end

    from dbo.MyTable


    Kindest Regards,

    Sureshkumar Ramakrishnan

  • Why????

    As Tyson said, just multiply by -1.

    positive values become negative ( 1 * -1 = -1).

    negative values become positive (-1 * -1 = 1).

    Thats what the original request was for!

    No need for conditional logic, and abs() only provides the absolute value which is always positive, not what was requested.

    Steve

  • I can't believe that I see this question for the second time. I feel obligated to quote the response I wrote some time ago, in another group:

    Well, this is a complicated question and it deserves a complicated answer
    Let's create a table with test data first:
     
    CREATE TABLE Numbers (X int)
     
    INSERT INTO Numbers VALUES (-7)

    INSERT INTO Numbers VALUES (0)

    INSERT INTO Numbers VALUES (20)

     
    I can think of a couple of ways to solve the problem:
     
    SELECT X, CONVERT(int, CONVERT(varbinary(4),0x100000000 - CONVERT(bigint,X))) as N FROM Numbers
     
    SELECT X, CASE WHEN SIGN(X)<0 THEN SIGN(X)*X ELSE (SIGN(X)-2 )*X END as N FROM Numbers
     
    But how about the obvious way:
     
    SELECT X, -X as N FROM Numbers
     
    Razvan

Viewing 7 posts - 1 through 6 (of 6 total)

You must be logged in to reply to this topic. Login to reply