SQL MERGE to remote (linked) server table

白昼怎懂夜的黑 提交于 2019-12-21 07:55:52

问题


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 some research online and couldn’t find any related information. If it is possible how would you setup the source and target statements?


回答1:


To reiterate the comment by @Mikael Eriksson, yes, you can. The target of a MERGE cannot be remote, but the source of a MERGE can be remote. So, if you can run the MERGE statement from your server in FL, then it is quite possible. For example, you could run something like this on your remove server in FL:

MERGE INTO "local FL table" USING "CT server"."database"."schema"."same table" ON ...



回答2:


Apparently my research wasn't good enough, it’s stated right on MSDN: “target_table cannot be a remote table” ... so that answers this question...




回答3:


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


来源:https://stackoverflow.com/questions/15236961/sql-merge-to-remote-linked-server-table

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!