SQL MERGE to remote (linked) server table

前端 未结 3 2177
死守一世寂寞
死守一世寂寞 2021-02-13 22:23

Is it possible to utilize the SQL MERGE function on a linked server\'s database table? The end goal is to synchronize the remote table with our local SQL server table. I’ve done

3条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-02-13 22:39

    Yoy can always use EXEC('SQL CODE HERE')AT YOUR_LINKED_SERVER in your server, maybe as a Stored Procedure.

    This will execute the query you want on your linked server so you could merge a local table (target_table) with a server table (source).

    This is a code I use in a Stored Procedure in my Server that its called from the client. Client exec stored procedure in server->Server Exec Query to update different linked servers (clients) with the same informacion (employees)

        EXEC('
    SET IDENTITY_INSERT PVBC.DBO.empleadas ON
    
    MERGE INTO PVBC.DBO.empleadas A
    USING(
        SELECT id_empleada, nombre, apellidos
        FROM SERVIDOR.PVBC_SERVIDOR.DBO.empleadas) TA
    ON (A.id_empleada =TA.id_empleada)
    WHEN MATCHED THEN
    UPDATE 
        SET A.nombre=TA.nombre,
            A.apellidos=TA.apellidos
    WHEN NOT MATCHED THEN
    
        INSERT 
            (id_empleada, nombre, apellidos)
        VALUES
            (id_empleada, nombre, apellidos);
    
    SET IDENTITY_INSERT PVBC.DBO.empleadas OFF
    ')AT MEGA --This is one of my linked servers
    

提交回复
热议问题