2

仅当存在较早的插入日期时,我才尝试更新表InsertDate中所有不同的AccIdAccNameHolder组合的。#tmpResults

表模式是这样的:

#tmpResults

Trans | AccId | AccountNameHolder | EarlyDate | CardType 

位置集合

Id | AccId | InsertDate | BtchId

卡错误

AccId | AccNameHolder | BtchId | TransId

这是我到目前为止所尝试的:

UPDATE  RES  
SET     EarlyDate = pc.InsertDate   
FROM  ( dbo.PositionCollection pc    
        LEFT JOIN dbo.CardErrors ce ON ce.BtchId = pc.BtchId AND pc.id =     ce.Transid  )    
    INNER JOIN #tmpResults RES   
ON      RES.AccId = pc.AccId    
AND     RES.AccNameHolder = ce.AccNameHolder    
WHERE   RES.EarlyDate = (SELECT MIN(InsertDate) FROM PostionCollection)    
AND     RES.AccId = pc.AccId    
AND     RES.AccNameHolder = ce.AccNameHolder
4

2 回答 2

0

在 UPDATE 语句中使用派生表

UPDATE x
SET x.EarlyDate = x.InsertDate  
FROM  ( 
       SELECT RES.EarlyDate, pc.InsertDate
       FROM dbo.PositionCollection pc
         LEFT JOIN dbo.CardErrors ce ON ce.BtchId = pc.BtchId AND pc.id = ce.Transid
         INNER JOIN #tmpResults RES ON RES.AccId = pc.AccId
           AND RES.AccNameHolder = ce.AccNameHolder
       WHERE RES.EarlyDate = (SELECT MIN(InsertDate) FROM PostionCollection) AND RES.AccId = pc.AccId
         AND RES.AccNameHolder = ce.AccNameHolder
       ) x

更新 27.11.2012

UPDATE x
SET x.EarlyDate = x.InsertDate
FROM  (
       SELECT RES.EarlyDate, m.InsertDate
       FROM dbo.PositionCollection pc
         LEFT JOIN dbo.CardErrors ce ON ce.BtchId = pc.BtchId AND pc.id = ce.Transid
         INNER JOIN #tmpResults RES ON RES.AccId = pc.AccId AND RES.AccNameHolder = ce.AccNameHolder
         INNER JOIN (SELECT MIN(InsertDate) AS InsertDate FROM PostionCollection) m
           ON RES.EarlyDate = m.InsertDate 
       ) x
于 2012-11-26T16:38:23.763 回答
0

这是一些更通用的解决方案,对于 InsertDate 为空的情况,您可以将它们与 DateDiff 一起使用,以将条件更改为较早、较晚或其他或类似的

OldInstDate <= COALESCE(NewInstDate, OldInstDate)

条件更新可以在 select 语句中实现,所以......

SET InsertDate = COALESCE(InsertDate, NewInsertDate) WHERE...

或者

SET InsertDate = CASE WHEN InsertDate IS NULL THEN NewInsertDate 
                      ELSE InsertDate END

或者

WHERE ...
AND InsertDate IS NULL

有关子查询的真正明确帮助 http://allenbrowne.com/subquery-01.html 我认为这可能是我见过的最好的,http://allenbrowne.com/subquery-02.html用于故障排除

于 2012-11-26T16:24:54.080 回答