Home Forums SQL Server 2008 T-SQL (SS2K8) How to update the same column multiple times in an UPDATE statement? RE: How to update the same column multiple times in an UPDATE statement?

  • I can't remember if it's true, or maybe my mind is playing tricks on me, but an update will only update rows once even if a correspondant select would show multiple lines.

    Here's a trick that might be adequate to your situation, but I can't claim it will be good enough performance wise.

    WITH rowsCTE AS(

    SELECT *, ROW_NUMBER() OVER(PARTITION BY Name ORDER BY ExDate) rn

    FROM @Splits

    ),

    recCTE AS(

    SELECT *

    FROM rowsCTE

    WHERE rn = 1

    UNION ALL

    SELECT row.Name, row.ExDate, row.ShareIn * rec.ShareIn, row.ShareOut * rec.ShareOut, row.rn

    FROM rowsCTE row

    JOIN recCTE rec ON row.Name = rec.Name

    AND row.rn = rec.rn + 1

    )

    UPDATE s

    SET ClosePrice = ClosePrice * Share

    FROM @StockPrice s

    CROSS APPLY( SELECT TOP 1 ShareOut / ShareIn AS Share FROM recCTE sp WHERE s.Name = sp.Name

    AND s.PriceDate >= sp.ExDate

    ORDER BY sp.ExDate DESC )x

    Luis C.
    General Disclaimer:
    Are you seriously taking the advice and code from someone from the internet without testing it? Do you at least understand it? Or can it easily kill your server?

    How to post data/code on a forum to get the best help: Option 1 / Option 2