TSQL How To Synchronize Between 2 Tables

This query work to find out any difference between 2 tables and return Only The Difference Row, Or Not There Row.

if the union all Group Count return 2 meaning it’s the same ,if 1 Than there’s difference. You can put on temporary table

SELECT MIN(tableName),Column1,Column2 .. N
    FROM
    (
    --sync 
    SELECT 'Table 1' AS tableName,Column1,Column2 .. N
    FROM
    Table1
    
    UNION ALL
    SELECT 'Table 2' AS tableName,Column1,Column2 .. N
    FROM
    Table2
 
    )
    tmp
    GROUP BY Column1,Column2 ..N
    --1 means have difference, 2 means identical
    HAVING COUNT(*)=1
    ORDER BY Column1,Column2 ..N

After That , Do your Insert Update Delete Logic From The Results.

Share this post: | | | |
Published Saturday, December 05, 2009 9:54 AM by cipto

Comments

# re: TSQL How To Synchronize Between 2 Tables

Thursday, December 10, 2009 4:25 AM by Kasim.Wirama

In SQL Server 2008, you can do insert/update/delete and select in only one statement using MERGE.

# re: TSQL How To Synchronize Between 2 Tables

Thursday, December 10, 2009 11:07 AM by cipto

Ok.. i've take a look at it.. still 2005 :)

Cool..

Merge:"Performs insert, update, or delete operations on a target table based on the results of a join with a source table. For example, you can synchronize two tables by inserting, updating, or deleting rows in one table based on differences found in the other table"