使用派生表更新无法正常工作

时间:2014-06-19 16:29:48

标签: sql sql-server-2008

请参阅以下查询:

update dbusns 
set thisdate = created 
from 
    (select 
        MAX(created) AS CREATED, DBCUSTODY.REFERENCE 
     from dbusns 
     inner join [server].Custody.DBO.dbcustody on dbusns.urns = dbcustody.reference
     where dbusns.datasetname = 'CUSTODY' 
     group by dbcustody.reference) As CustodyDateTable 
WHERE 
   dbusns.urns = CustodyDateTable.reference 
   and dbusns.urns = '1' 

以下查询返回01/01/2011

select 
    MAX(created) AS CREATED, DBCUSTODY.REFERENCE 
from 
    dbusns 
inner join 
    server.database.DBO.dbcustody on dbusns.urns = dbcustody.reference
where 
    dbusns.datasetname = 'CUSTODY' AND DBCUSTODY.REFERENCE = '1'

但是,以下查询返回31/10/2011(在运行查询1之后):

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

以下查询返回两行(2011年10月31日和2011年11月11日):

select created 
from [server].Custody.DBO.dbcustody 
where reference = '1'

为什么查询3返回31/10/2011?它应该返回01/11/2011?这与执行计划/链接服务器有关吗?

2 个答案:

答案 0 :(得分:2)

您的UPDATE语法似乎不符合您的要求。在这种情况下,最好的方法是使用INNER JOIN

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

答案 1 :(得分:0)

我认为你的update语法是正确的,除了一件小事。考虑这一行:

update dbusns set thisdate = created from ( . . .

created列 - 我猜 - 在dbusns。因此,它只是将thisdate设置为创建的值i在同一个表中。

您可以使用表别名来解决此问题:

update dbusns set thisdate = CustodyDateTable.created from ( . . .