编程语言
首页 > 编程语言> > c#-更新满足datediff约束的所有行的int列?

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

作者:互联网

我有一个每30秒运行一次的函数,我想更新当前时间所在的所有行中的一列-table.lastStoredTime> 5分钟.

lastStoredTime是datetime列,我似乎无法正常工作.

尝试(不更新行)

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

解决方法:

测试设置:

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())

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

选择输出:

+----+---------------------+--------+-------+
| 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 |
+----+---------------------+--------+

使用案例表达式进行更新:

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 |
+----+---------------------+--------+

标签:azure-functions,timestamp,sql,c,sql-server
来源: https://codeday.me/bug/20191025/1931017.html