Home Forums SQL Server 2005 SQL Server Newbies How to add two column and the to put the result on the next row? RE: How to add two column and the to put the result on the next row?

  • ashishjain (2/6/2013)


    Hi angjoni,

    You can use below code to perform this operation:

    create table test99 (column1 int, column2 int, result int)

    insert into test99

    values

    (50,1500,0),

    (100,0,0),

    (40,0,0),

    (30,0,0)

    declare @col2 int = 1500

    select * from test99

    update test99

    set @col2 = result = @col2 + column1,

    column2 = @col2

    from test99

    select * from test99

    drop table test99

    I'll add an explicit warning to what Koen said:

    While it may work in the example case, the above code violates at least 3-4 of the rules in that article.

    I won't tell you what they are because you need to read that article and understand the rules before you use this approach in a production system.


    My mantra: No loops! No CURSORs! No RBAR! Hoo-uh![/I]

    My thought question: Have you ever been told that your query runs too fast?

    My advice:
    INDEXing a poor-performing query is like putting sugar on cat food. Yeah, it probably tastes better but are you sure you want to eat it?
    The path of least resistance can be a slippery slope. Take care that fixing your fixes of fixes doesn't snowball and end up costing you more than fixing the root cause would have in the first place.

    Need to UNPIVOT? Why not CROSS APPLY VALUES instead?[/url]
    Since random numbers are too important to be left to chance, let's generate some![/url]
    Learn to understand recursive CTEs by example.[/url]
    [url url=http://www.sqlservercentral.com/articles/St