Search code examples
sqlsql-serverstored-proceduressql-server-2000

Sync two tables one way in the same database using stored procedure


I've 2 identical tables, one will be updated and the other no, so I want to write stored procedure to check the updates for existing record in table 2 and if not exist to insert the record from table 1 to table 2.

Table 1

    | Field1 | Field2 | Field3 |
    | ------ | ------ | -----: |
    |  A     |  1     |   $10  |
    |  B     |  2     |   $20  |
    |  C     |  2     |   $21  |


Table 2

    | Field1 | Field2 | Field3 |
    | ------ | ------ | -----: |
    |  A     |  3     |   $13  |
    |  B     |  2     |   $20  |

What the stored procedure will do in this sample, it'll update row (B) in Table 2 with the data in Table 1 and insert row (C) to Table 2.


Solution

  • For the update part, you can check using the ID or any identifier field in your database:

    UPDATE t2 
    SET t2.field2 = t1.field2 and t2.field3 = t1.field3 
    FROM table2 AS t2
    INNER JOIN table1 AS t1 
          ON t2.field1=t1.field1
    

    And just add the insert part from the reply above after the update statement.