使用另一个表中的数据更新一个表中的行

时间:2014-09-23 11:36:02

标签: sql sql-server

我有两个表,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]

3 个答案:

答案 0 :(得分:2)

使用联接:

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

答案 1 :(得分: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])

答案 2 :(得分: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]