我在sql server 2012中有一个表,其中列名为Duration as Time datatype.i想要根据日期差异更新此列,方法是将差异添加到此持续时间列中。我可以在SP中执行此操作。 / p>
ID StartDate EndDate Duration
1 2017-02-27 09:10:35 2017-02-27 09:25:35 00:15
2 2017-02-27 09:26:35 2017-02-27 09:36:35 00:25
Durtion总是不到24小时。
答案 0 :(得分:2)
一种方法是:
update t
set duration = cast(dateadd(ms, datediff(ms, startdate, enddate), 0) as time);
答案 1 :(得分:1)
这很简单。只需使用简单的算术运算:
DECLARE @TABLE TABLE (Start DATETIME, Finish DATETIME, Duration TIME);
INSERT INTO @TABLE VALUES ('02/28/2017 08:00','02/28/2017 08:30','');
INSERT INTO @TABLE VALUES ('02/28/2017 09:00','02/28/2017 09:40','');
INSERT INTO @TABLE VALUES ('02/28/2017 10:02','02/28/2017 11:53','');
INSERT INTO @TABLE VALUES ('02/28/2017 11:56','02/28/2017 12:45','');
INSERT INTO @TABLE VALUES ('02/28/2017 13:45','02/28/2017 23:59','');
UPDATE @TABLE
SET Duration = Finish - Start;
SELECT * FROM @TABLE;
返回:
Start Finish Duration
---------------------------------------------------------
28/02/2017 08:00:00 28/02/2017 08:30:00 00:30:00
28/02/2017 09:00:00 28/02/2017 09:40:00 00:40:00
28/02/2017 10:02:00 28/02/2017 11:53:00 01:51:00
28/02/2017 11:56:00 28/02/2017 12:45:00 00:49:00
28/02/2017 13:45:00 28/02/2017 23:59:00 10:14:00
唯一需要注意的是,他们需要在同一天。你明确表示持续时间不会超过一天,所以应该没问题。
如果您想将结果添加到Duration
的原始值,那么您只需将其添加到...
INSERT INTO @TABLE VALUES ('02/27/2017 08:00','02/28/2017 08:30','00:15');
INSERT INTO @TABLE VALUES ('02/28/2017 09:00','02/28/2017 09:40','00:14');
INSERT INTO @TABLE VALUES ('02/28/2017 10:02','02/28/2017 11:53','00:13');
INSERT INTO @TABLE VALUES ('02/28/2017 11:56','02/28/2017 12:45','02:16');
INSERT INTO @TABLE VALUES ('02/28/2017 13:45','02/28/2017 23:59','00:17');
UPDATE @TABLE
SET Duration = Duration + (Finish - Start);
返回:
Start Finish Duration
---------------------------------------------------------
27/02/2017 08:00:00 28/02/2017 08:30:00 00:45:00
28/02/2017 09:00:00 28/02/2017 09:40:00 00:54:00
28/02/2017 10:02:00 28/02/2017 11:53:00 02:04:00
28/02/2017 11:56:00 28/02/2017 12:45:00 03:05:00
28/02/2017 13:45:00 28/02/2017 23:59:00 10:31:00
答案 2 :(得分:0)
UPDATE [TABLE] SET [DURATION] = CONVERT(varchar(5),DATEADD(分钟,DATEDIFF(MINUTE,StartDate,EndDate),0),114);
答案 3 :(得分:0)
其他任何一个答案都没有尝试使你期望的持续时间相加。
DECLARE @TABLE TABLE (ID INT, StartTime DATETIME, EndTime DATETIME, Duration TIME);
INSERT INTO @TABLE VALUES (1, '02/28/2017 01:00','02/28/2017 06:30','');
INSERT INTO @TABLE VALUES (2, '02/28/2017 09:00','02/28/2017 23:40','');
INSERT INTO @TABLE VALUES (3, '03/01/2017 10:02','03/01/2017 21:53','');
UPDATE t
SET Duration=
CONVERT(TIME,
(
SELECT DATEADD(ms, SUM(DATEDIFF(ms, '00:00:00.000', EndTime - StartTime)), '00:00:00.000')
FROM @TABLE it
WHERE it.EndTime<= t.EndTime
)
)
FROM @TABLE t;
SELECT * FROM @TABLE;