Question

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.

Was it helpful?

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.

OTHER TIPS

Have you considered something like this?

INSERT INTO Table2
(
     Field1
    ,Field2
    ,Field3
)
SELECT 
     Field1
    ,Field2
    ,Field3 
FROM Table1 
WHERE NOT EXISTS (
                  SELECT
                       Field1
                      ,Field2
                      ,Field3 
                  FROM Table2
                  )

Of course, if you have an identity seed, then you just take the MAX(Value) instead.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top