2011-09-16 29 views
0

我有一個名爲node_status表,有三列:如何的當前時間和列的時間差的基礎上更新表

  1. id (int)
  2. status (bit)
  3. modifiedtime (smalldatetime)

我想運行一個查詢,如果表中的任何一行包含modifiedtime值超過5 mi在當前時間之前nutes,然後將status列設置爲0(false)。

任何機構可以告訴我如何做到這一點? (使用SQL Server)

感謝

回答

2

當你想要做的一個基於當前時間的查詢可以使用getdate(),並使用dateadd函數從日期中添加或刪除時間量。因此:

update 
    node_status 
set 
    status = 0 
where 
    modifiedtime < dateadd(minute, -5, getdate()) 
1

可以使用DATEADD功能前五分鐘來計算的日期/時間,然後modifiedtime列與此值:

UPDATE node_status SET status = 0 WHERE modifiedtime <= dateadd(minute, -5, CURRENT_TIMESTAMP) 
3

查詢

UPDATE node_status 
SET [Status] = 0 
WHERE DATEDIFF(n, ModifiedTime, CURRENT_TIMETAMP) >= 5 

將做的工作,但是,如果你的node_status表很大,那麼性能會因表/索引掃描糟糕。如果您有ModifiedTime索引:

DECLARE @ThresholdTime DATETIME 
SET @ThresholdTime = DATEADD(n, -5, CURRENT_TIMESTAMP) 

UPDATE node_status 
SET [Status] = 0 
WHERE ModifiedTime <= @ThresholdTime 

,甚至更好,如果大多數記錄具有node_status = 0(即選擇性)

UPDATE node_status 
SET [Status] = 0 
WHERE ModifiedTime <= @ThresholdTime 
    AND [Status] = 1 -- You've stated that status is a bit - I've assumed not nullable. 
相關問題