使用select语句在linkedserver表上执行更新

时间:2017-08-07 14:47:06

标签: sql sql-server sql-update linked-server

我尝试在链接服务器上的表上执行更新,使用当前服务器上的表中的信息,并且查询花了2个小时来更新单个测试行,这里是我的查询

UPDATE OPENQUERY (LINKEDSERVER, 'SELECT FIELD1, FIELD2, FIELD3, FIELD4 FROM 
SPV.DBO.TESTTABLE')
SET FIELD1 = LT.FIELD1, 
    FIELD2 = LT.FIELD2, 
    FIELD3 = LT.FIELD3, 
    FIELD4 = LT.FIELD4
FROM OPENQUERY (LINKEDSERVER, 'SELECT FIELD1, FIELD2, FIELD3, FIELD4 FROM 
SPV.DBO.TESTTABLE') L
INNER JOIN LOCALTESTTABLE LT ON LT.FIELD1 = L.FIELD1 COLLATE 
Latin1_General_CI_AS    
AND LT.FIELD2 = L.FIELD2 COLLATE Latin1_General_CI_AS   

1 个答案:

答案 0 :(得分:0)

这对你有用吗?

UPDATE L
    SET FIELD1 = LT.FIELD1, 
        FIELD2 = LT.FIELD2, 
        FIELD3 = LT.FIELD3, 
        FIELD4 = LT.FIELD4
FROM LINKEDSERVER.SPV.DBO.TESTTABLE INNER JOIN
     LOCALTESTTABLE LT
     ON LT.FIELD1 = L.FIELD1 COLLATE Latin1_General_CI_AS AND
        LT.FIELD2 = L.FIELD2 COLLATE Latin1_General_CI_AS;

四部分命名比OPENQUERY()简单。

您的版本也可以使用,但您需要使用update的别名:

UPDATE L
    SET FIELD1 = LT.FIELD1, 
        FIELD2 = LT.FIELD2, 
        FIELD3 = LT.FIELD3, 
        FIELD4 = LT.FIELD4
FROM OPENQUERY (LINKEDSERVER, 'SELECT FIELD1, FIELD2, FIELD3, FIELD4 FROM 
SPV.DBO.TESTTABLE') L INNER JOIN
     LOCALTESTTABLE LT
     ON LT.FIELD1 = L.FIELD1 COLLATE Latin1_General_CI_AS AND
        LT.FIELD2 = L.FIELD2 COLLATE Latin1_General_CI_AS  ;

否则,您正在更新表中的所有行。