views:

107

answers:

3

Hi I am looking for A solution to update values in table1 only if the values change. I mean compare to tableb and update only the changed values

A: 

You could use a trigger on the source table that updates the target table.

However if there's large volume that could slow inserts/updates on the source quite badly. In which case, I'd make the trigger insert into a 3rd table. A scheduled job could then process that table and delete records (with appropriate use of transactions, of course).

An entirely different approach would be to move the triggering up one layer into your application, and use a message-based approach. In this situation you get the best of both worlds, because the process listening for messages will process them in order as fast as it can, leading to almost real-time updates of the target table.

So you can have your cake, and eat it.

Neil Barnwell
+2  A: 

An alternative to neils solution is to use binary checksum and store that in a field in your table then compare against that

Not saying its a better solution, just giving you some options.

Chris Klepeis
Yes, a simpler approach. If load is high though, that could end up being the source of locking problems on the source table while the process reading it does it's thing. Also, it's kind've polluting the data model for the source table by adding this info when it's not actually part of the data represented by the table.
Neil Barnwell
Neil, polluting the data model? A well-designed database often has fields that are not intended to be seen by users and thus are not in the data model. There are fields used to manage data not information. Things like the date the record was created and the last person to update the rows. If you have correctly written your application code to pull only the data you want and not everything (which you should do for performance reasons among other reasons), this is a non-problem. If you used select * (which should not be done on a production database) then it is a problem.
HLGEM
This can work and be faster than joining on every table in the record. It is better to create and update this at record creation and update than to try to calculate 10,000,000 binary_checksums at run time.
HLGEM
A: 

for multiple rows at a time try:

UPDATE a
    SET IntCol=b.IntCol
       ,varcharCol=b.varcharCol
       ,DatetimeCol=b.DatetimeCol
    FROM TableA           a
        INNER JOIN (SELECT pk,IntCol,varcharCol,DatetimeCol FROM TableA
                    EXCEPT
                    SELECT pk,IntCol,varcharCol,DatetimeCol FROM TableB
                   ) dt ON a.pk=dt.pk
KM