locked
Update columns if data exists oterwise insert without using parameters RRS feed

  • Question

  • User1052662409 posted

    Hello Everyone,

    I need to transfer some of columns data from from one table to another.

    I can do it easily using the below query

    INSERT INTO table2 (column1, column2, column3, ...)
    SELECT column1, column2, column3, ...
    FROM table1

    Here I have a condition, that id the mentioned columns data already exists in table2 then it should update the data otherwise it should insert the remaining data which is not exists in table2 and I don't want to use any external parameter for that.

    Please suggest.

    Thanks

    Tuesday, December 1, 2020 6:57 AM

Answers

  • User452040443 posted

    Hi,

    I believe you can use the Merge statement:

    MERGE table2 as t2
    USING table1 as t1 ON t1.Id = t2.Id
    WHEN MATCHED THEN
        UPDATE SET t2.column1 = t1.column1, t2.column2 = t1.column2, t2.column3 = t1.column3
    WHEN NOT MATCHED THEN
        INSERT (column1, column2, column3)
        VALUES (t1.column1, t1.column2, t1.column3)
    

    Hope this help

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, December 1, 2020 1:18 PM