Swaping Columns in Single Query

  • Hi,

    I Have Table called Numbers which Contains Columns Num1 and Num2 of same data type. I want a Single Query to swap the rows in the Table. The condition is not to use Temporary Table.

  • Swap how? By looking, or permanently? (assume you mean 'swap columns' rather than 'rows')

    -- just looking

    select num2, num1 from numbers

    -- permanent change

    update numbers

    set    num1 = num2,

           num2 = num1

    /Kenneth

  • You can try this

    create table Numbers (num1 int,num2 int)

    insert into Numbers values(1,2)

    insert into Numbers values(3,4)

    insert into Numbers values(5,6)

    declare @temp int

    Update Numbers

    set @temp=Num1, Num1=Num2, Num2=@temp

  • Yes I got it.Thanks for taking time to reply......

    Can we Write a Query to find the Max Number of two given numbers?  If so please help me

  • I tried the Query I got it.

    The Query is

    declare @num1 int

    declare @num2 int

    set @num1 = 1

    set @num2 = 1

    select (case when @num1 > @num2 then @num1 else @num2 end)

  • Just for grins...

    DECLARE @Num1 FLOAT

    DECLARE @Num2 FLOAT

        SET @Num1 = -1.2

        SET @Num2 = -3.4

     SELECT Largest = (ABS(Num2-Num1)+(Num2+Num1))/2

    --Jeff Moden


    RBAR is pronounced "ree-bar" and is a "Modenism" for Row-By-Agonizing-Row.
    First step towards the paradigm shift of writing Set Based code:
    ________Stop thinking about what you want to do to a ROW... think, instead, of what you want to do to a COLUMN.

    Change is inevitable... Change for the better is not.


    Helpful Links:
    How to post code problems
    How to Post Performance Problems
    Create a Tally Function (fnTally)

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

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