SQL Server - 自上一行创建以来的时间列

时间:2016-04-28 17:20:18

标签: sql sql-server

我有一个像这样结构的表

CREATE TABLE log (
  id                 BIGINT            IDENTITY (1, 1) PRIMARY KEY,
  datetime_created   DATETIME NOT NULL DEFAULT (getdate()),
  message            VARCHAR(MAX)
)

我想添加第四列time_since,默认情况下会查看上一行的datetime_created字段并获取时间差异并将其保存在新行的{{1}中}专栏。

关于如何实现这一目标的任何想法?

编辑:作为一个说明,我受限于使用SQL Server 2008

3 个答案:

答案 0 :(得分:1)

我建议你不要使用 LAG 来计算它。这样,如果日期发生变化,您将无需更改此第二个字段。

实施例

CREATE TABLE log (
  id                 BIGINT            IDENTITY (1, 1) PRIMARY KEY,
  datetime_created   DATETIME NOT NULL DEFAULT (getdate()),
  message            VARCHAR(MAX)
)

insert into log values ('2016-01-01', 'first');
insert into log values ('2016-01-02T12:21:23', 'second');

SELECT l.id, l.datetime_created, l.message, DATEDIFF(SECOND, LAG(l.datetime_created) OVER (ORDER BY l.id), l.datetime_created)
FROM log l

答案 1 :(得分:1)

您可以使用而不是触发器来执行此操作

create table log
(
    id bigint identity(1, 1) primary key,
    datetime_created datetime not null default (getdate()),
    message varchar(max),
    time_since int not null
)
go

create trigger is_log on log
instead of insert
as
    insert into log (datetime_created, message, time_since)
    select datetime_created, message, 
        datediff(ss, isnull((select max(datetime_created) from log), getdate()), datetime_created)
    from inserted
go

insert into log (message) 
values ('Message 1')

waitfor delay '00:00:02';

insert into log (message) 
values ('Message 2')

waitfor delay '00:00:04';

insert into log (message) 
values ('Message 3')

waitfor delay '00:00:06';

insert into log (message)
select message + 'multi insert'
from log
go

select *
from log

答案 2 :(得分:0)

插入新行时,为什么不插入一个等于DATEDIFF的值(SECOND,(SELECT MAX(datetime_created)FROM log),CURRENT_TIMESTAMP)