更新满足 datediff 约束的所有行的 int 列?

Updating int column of all rows that satisfy datediff constraint?

我每 30 秒有一个函数 运行,我想更新 current time - table.lastStoredTime > 5 minutes.

所在的所有行中的列

lastStoredTime 是日期时间列,我似乎无法正常工作。

尝试(不更新行)

SELECT  
    DATEDIFF(MINUTE, t.lastStoredTime, CURRENT_TIMESTAMP) AS Mtime 
FROM Transaction_tbl t 
WHERE 
    AND DATEDIFF(MINUTE,t.lastStoredTime, CURRENT_TIMESTAMP) > 5

使用以下 sql 语句

SELECT DATEDIFF(MINUTE, t.lastStoredTime, GetDate()) FROM Transaction_tbl t WHERE DATEDIFF(MINUTE,t.lastStoredTime, GetDate()) > 5

如果要更新列,为什么要使用 select 语句?
您应该使用更新语句:

UPDATE Transaction_tbl 
SET <YourColumnName> = <Value>
WHERE t.lastStoredTime <= DATEADD(MINUTE, -5, GETDATE())

当然,<YourColumnName><Value>是占位符。

请注意我没有使用 DATEDIFF,而是将列的值与当前日期和时间之前 5 分钟的值进行比较(使用 DATEADDGETDATE) .
这样做的原因是使用 DATEDIFF 版本会阻止 SQL 服务器使用任何可能与 sql 语句相关的索引(而不仅仅是 DATEDIFF,任何函数都会去做吧)。
通过将列的实际值与计算值进行比较,SQL服务器可以使用任何可能有助于提高性能的索引。

测试设置:

create table Transaction_tbl (id int identity(1,1) not null, lastStoredTime datetime2(7), intcol int)
insert into Transaction_tbl 
          select dateadd(minute,-7,sysdatetime()), 0
union all select dateadd(minute,-6,sysdatetime()), 0
union all select dateadd(minute,-5,sysdatetime()), 0
union all select dateadd(minute,-4,sysdatetime()), 0
union all select dateadd(minute,-3,sysdatetime()), 0

查询:

/* select */
select *,
  datediff(minute, t.lastStoredTime, sysdatetime()) as Mtime 
from Transaction_tbl t 
where t.lastStoredTime < dateadd(minute,-5,sysdatetime())

/* as an update */
update t
  set intcol = intcol+1
output inserted.*
from Transaction_tbl t 
where t.lastStoredTime < dateadd(minute,-5,sysdatetime())

rextester 演示:http://rextester.com/TXYXT83237

select 输出:

+----+---------------------+--------+-------+
| id |   lastStoredTime    | intcol | Mtime |
+----+---------------------+--------+-------+
|  1 | 2017-08-22 19:31:52 |      0 |     7 |
|  2 | 2017-08-22 19:32:52 |      0 |     6 |
|  3 | 2017-08-22 19:33:52 |      0 |     5 |
+----+---------------------+--------+-------+

更新输出:

+----+---------------------+--------+
| id |   lastStoredTime    | intcol |
+----+---------------------+--------+
|  1 | 2017-08-22 19:31:52 |      1 |
|  2 | 2017-08-22 19:32:52 |      1 |
|  3 | 2017-08-22 19:33:52 |      1 |
+----+---------------------+--------+

使用 case 表达式更新:

update t
  set intcol = case when t.lastStoredTime < dateadd(minute,-5,sysdatetime()) 
      then intcol+1
      else intcol-1
      end
output inserted.*
from Transaction_tbl t 

输出:

+----+---------------------+--------+
| id |   lastStoredTime    | intcol |
+----+---------------------+--------+
|  1 | 2017-08-22 19:47:14 |      2 |
|  2 | 2017-08-22 19:48:14 |      2 |
|  3 | 2017-08-22 19:49:14 |     -1 |
|  4 | 2017-08-22 19:50:14 |     -1 |
|  5 | 2017-08-22 19:51:14 |     -1 |
+----+---------------------+--------+