我有一个每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
答案 0 :(得分:4)
测试设置:
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
选择输出:
+----+---------------------+--------+-------+
| 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 |
+----+---------------------+--------+
答案 1 :(得分:0)
使用以下sql语句
SELECT DATEDIFF(MINUTE, t.lastStoredTime, GetDate())
FROM Transaction_tbl t
WHERE DATEDIFF(MINUTE,t.lastStoredTime, GetDate()) > 5
答案 2 :(得分:0)
如果要更新列,为什么要使用select语句?
您应该使用更新声明:
UPDATE Transaction_tbl
SET <YourColumnName> = <Value>
WHERE t.lastStoredTime <= DATEADD(MINUTE, -5, GETDATE())
对于cource,<YourColumnName>
和<Value>
是占位符。
请注意我没有使用DATEDIFF
,而是将列的值与当前日期和时间之前的5分钟进行比较(使用DATEADD
和GETDATE
)。<登记/>
原因是使用DATEDIFF
版本会阻止SQL Server使用可能与sql语句相关的任何索引(而不只是DATEDIFF
,任何函数都会这样做。)
通过将列的实际值与计算值进行比较,SQL Server可以使用任何可能有助于提高性能的索引。