How to update one column if second column matches

  • Hi,

    I have 2 tables, from which i have to update as below

    table Source: col a, col b

    table destination: col d, col e

    if source.b = destination.e then

    update destination

    set d = a

    Any clue how to do...

    Shaun

  • Barring any missing criteria, this should be an UPDATE...FROM query:

    UPDATE Destination

    SET Destination.d = Source.a

    FROM Destination

    INNER JOIN Source

    ON Destination.e = Source.b

    Test this first, of course, before firing it off as an actual UPDATE.

    - 😀

  • I had it somewhat different, maybe too complex:

    ;with which_col_a_cte (col_a, col_d, col_e) on (

    select s.col_a, d.col_d, d.col_e

    from destination d inner join

    source s on d.e = s.b

    )

    update destination

    set col.d = cte.col.a

    from destination d inner join

    which_col_a_cte cte on d.col_e = cte.col_e

    and d.col_d = cte.col_d

    Without any real data I wasn't able to test it, but I think it looks good.

    Kurt W. Zimmerman
    SR DBA
    Lefrak Organization
    New York, NY

    http://www.linkedin.com/in/kurtwzimmerman

  • Hi Kurt it is complex but nice one,i thing you used CTE for update process i am stater of CTE as of now i have seen only select queries but i hope it will help me on that type of scenarios Thanks:-).

  • hi kurt,

    I did had the query but was the performance issues..i was looking to use ssis components such as lookup..

    Shaun..

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

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