2014-09-23 166 views
0

我有两个表,CountLogsRegisterCountLogs。它们都具有相同的FK限制,所以我想将时间戳从一个传送到另一个。我如何在一个SQL语句中实现这一点?更新一个表中的行,使用另一个数据

E.g.

SELECT [DeviceSerial] 
     ,[LogEntryID] 
     ,[Timestamp] 
    FROM [dbo].[CountLogs] 

UPDATE RegisterCountLogs 
    SET Timestamp = [OTHERQUERY?].Timestamp 
    WHERE [DeviceSerial] = [OTHERQUERY?].[DeviceSerial] 
     AND [OTHERQUERY?][LogEntryID] = [OTHERQUERY?].[LogEntryID] 

回答

2

使用JOIN:

UPDATE RegisterCountLogs 
    SET Timestamp = [OTHERQUERY?].Timestamp 
    FROM  RegisterCountLogs 
    INNER JOIN [OTHERQUERY?]  ON RegisterCountLogs.DeviceSerial = [OTHERQUERY?].[DeviceSerial] 
           AND RegisterCountLogs.[LogEntryID] = [OTHERQUERY?].[LogEntryID] 
1

试试这个...

UPDATE R 
SET R.Timestamp = C.Timestamp 
FROM RegisterCountLogs R 
INNER JOIN [dbo].[CountLogs] C ON 
(R.[DeviceSerial] = C.[DeviceSerial] 
AND R.[LogEntryID] = C.[LogEntryID]) 
0
;With Cte_countlogs as 
(
    SELECT [DeviceSerial] 
    ,[LogEntryID] 
    ,[Timestamp] 
    FROM [dbo].[CountLogs] 
) 

UPDATE RegisterCountLogs 
SET Timestamp = Cte_countlogs .Timestamp 
from 
RegisterCountLogs 
JOIN Cte_countlogs ON RegisterCountLogs.DeviceSerial = Cte_countlogs .[DeviceSerial] 
AND RegisterCountLogs.[LogEntryID] = Cte_countlogs.[LogEntryID] 
相关问题