SQL Server - synchronizing 2 tables on 2 different databases

前端 未结 3 901
-上瘾入骨i
-上瘾入骨i 2020-12-13 03:04

I have 2 tables with same schema on 2 different databases on the same server with SQL Server 2008 R2. One table gets updated with data more often.

Now there is a nee

相关标签:
3条回答
  • 2020-12-13 03:17

    Using MERGE is your best bet. You can control each of the conditions. WHEN MATCHED THEN, WHEN UNMATCHED THEN etc.

    MERGE - Technet

    MERGE- MSDN (GOOD!)

    Example A: Transactional usage - Table Variables - NO

    DECLARE @Source TABLE (ID INT)
    DECLARE @Target TABLE (ID INT)
    
    INSERT INTO @Source (ID) VALUES (1),(2),(3),(4),(5)
    
    BEGIN TRANSACTION
    
    MERGE @Target AS T
    USING @Source AS S
    ON (S.ID = T.ID)
    WHEN NOT MATCHED THEN
        INSERT (ID) VALUES (S.ID);
    
    ROLLBACK TRANSACTION
    SELECT  'FAIL' AS Test,*
    FROM    @Target
    

    Example B: Transactional usage - Physical Tables

    CREATE TABLE SRC (ID INT);
    CREATE TABLE TRG (ID INT);
    
    INSERT INTO SRC (ID) VALUES (1),(2),(3),(4),(5)
    
    BEGIN TRANSACTION
    
    MERGE TRG AS T
    USING SRC AS S
    ON (S.ID = T.ID)
    WHEN NOT MATCHED THEN
        INSERT (ID) VALUES (S.ID);
    
    ROLLBACK TRANSACTION
    SELECT  'FAIL' AS Test,*
    FROM    TRG
    

    Example C: Transactional usage - Tempdb (local & global)

    CREATE TABLE #SRC (ID INT);
    CREATE TABLE #TRG (ID INT);
    
    INSERT INTO #SRC (ID) VALUES (1),(2),(3),(4),(5)
    
    BEGIN TRANSACTION
    
    MERGE #TRG AS T
    USING #SRC AS S
    ON (S.ID = T.ID)
    WHEN NOT MATCHED THEN
        INSERT (ID) VALUES (S.ID);
    
    ROLLBACK TRANSACTION
    SELECT  'FAIL' AS Test,*
    FROM    #TRG
    
    0 讨论(0)
  • 2020-12-13 03:19

    You can select from the different databases and use a cursor to loop the selected data. Within that cursor you can do some logic and update or delete from the target table.

    Also SQL 2008 has a nice new MERGE statement which you can use to select/insert/update in one T-SQL query. http://technet.microsoft.com/en-us/library/bb510625%28v=sql.105%29.aspx

    For more complex processes i use the first option. For more straight forward sync tasks i use the second option.

    As an extra option there is also Server Integration Services (SSIS): http://blogs.msdn.com/b/jorgepc/archive/2010/12/07/synchronize-two-tables-using-sql-server-integration-services-ssis-part-i-of-ii.aspx

    0 讨论(0)
  • 2020-12-13 03:34

    You probably can use sql server's tablediff.exe command line utility. It can do table-by-table, one-off compare between two tables and generate the sql automatically for you to sync the dest to the source.

    There's also a GUI wrapper around it http://code.google.com/p/sqltablediff/ which makes the job even easier. It will generate the command line for you.

    You can then create a scheduled task to run the command line, and then execute the generated sql scripts.

    0 讨论(0)
提交回复
热议问题