UPDATE与链接服务器无法正常工作

时间:2014-06-20 10:07:56

标签: sql sql-server

请参阅以下查询:

select thisdate,created from dbusns d
INNER JOIN (SELECT  MAX(created) created,
                    C.reference 
            FROM dbusns
            INNER JOIN [server].CUSTODYDB.DBO.dbcustody C
                ON dbusnS.urns = C.reference
            WHERE dbusns.datasetname = 'CUSTODY'
            GROUP BY C.reference) T on D.urns = T.reference
WHERE D.urns = '1' 

返回:2008-10-31 00:00:00.000,2008-11-01 00:00:00.000

然后我运行以下查询:

UPDATE D
SET thisdate = T.created
FROM dbusns D
INNER JOIN (SELECT  MAX(created) created,
                    C.reference 
            FROM dbusns
            INNER JOIN [server].CUSTODYDB.DBO.dbcustody C
                ON dbusnS.urns = C.reference
            WHERE dbusns.datasetname = 'CUSTODY'
            GROUP BY C.reference) T on D.urns = T.reference
WHERE D.urns = '1' 

然后我运行下面的查询,返回:2008-10-31 00:00:00.000(应该是:2008-11-01 00:00:00.000)

select THISDATE from dbusns where datasetname='CUSTODY' AND URNS='1'

已创建且ThisDate为日期时间。如果我将dbcustody中的记录数减少到29,598,则值会正确更新。我试图删除第29,598条记录,但这不起作用。

发生了什么事?它似乎是执行计划不正确,因为它发送的远程查询是:

SELECT TOP 1 created FROM dbcustody where reference='1' 

为什么不发送MAX语句/ ORDER BY创建desc?

1 个答案:

答案 0 :(得分:3)

编辑:删除了一些不相关的内容。

过去发生这种情况时,我通常采用OPENQUERY来解决这个问题。试试这个:

UPDATE D
SET thisdate = T.created
FROM dbusns D
INNER JOIN (SELECT MaxCreated, Reference FROM OPENQUERY(server, 'SELECT MAX(created) MaxCreated, reference
    FROM CUSTODYDB.DBO.dbcustody') as RemoteTable
    INNER JOIN dbusns ON dbusnS.urns = RemoteTable.reference
    WHERE dbusns.datasetname = 'CUSTODY'
    GROUP BY RemoteTable.reference) T ON D.urns = T.reference
WHERE D.urns = '1'