簡體   English   中英

使用另一個表中的數據更新一個表中的行

[英]Update rows in one table, with data from another

我有兩個表CountLogsRegisterCountLogs 它們都具有相同的FK約束,因此我想將時間戳從一個轉移到另一個。 如何在一個SQL語句中實現這一目標?

例如

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

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

使用聯接:

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

嘗試這個...

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])
 ;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]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM