time: '1145'
duration: 45
sum: '1230'
time: '0915'
duration: 30
sum: '0945' (not '945')
time: '1145'
duration: 45
sum: '1230'
time: '0915'
duration: 30
sum: '0945' (not '945')
CREATE TABLE timevalues
(
timestring VARCHAR(20) NOT NULL
, duration INT NOT NULL
);
INSERT INTO timevalues (timestring, duration) VALUES
('1145', 30),
('2345', 25),
('0815', 125);
SELECT timestring
, duration
, REPLACE(CONVERT(VARCHAR(5), DATEVALUE, 108), ':', '') AS newtimevalue
FROM
(
SELECT timestring
, duration
, DATEADD(MINUTE,
duration,
CAST(
( SUBSTRING(timestring, 1, 2) + ':' +
SUBSTRING(timestring, 3, 2)
) AS DATETIME
)
) AS DATEVALUE
FROM timevalues
) T1;
输出:
timestring duration newtimevalue
---------- -------- -------------
1145 30 1215
2345 25 0010
0815 125 1020
虽然不美观但可以得到您想要的结果:
create table #temp
(
militarytime varchar(4),
duration int
)
insert into #temp values('1410', 10)
insert into #temp values('0415', 5)
insert into #temp values('1145', 45)
insert into #temp values('0915', 30)
select left(replace(convert(varchar, dateadd(mi, duration, convert(datetime, convert(datetime, replace(militarytime, right(militarytime,2), ':' + right(militarytime,2))))), 114), ':', ''), 4)
from #temp
drop table #temp
Results:
1420
0420
1230
0945
注意 - 很可能有更好的方法 - 只是展示另一种选择。
我不知道为什么你需要以这种方式做这个。
个人而言,我会让数据类型保持在SQL-Server中自然的行为。格式化处理应该在客户端或数据库层之外的任何地方进行。将呈现考虑与数据考虑分开;)
话虽如此,我觉得我已经尽了自己的职责,使宇宙变得更好,所以现在可以告诉我们你实际想要我们做什么了!
REPLACE(
CONVERT(
VARCHAR(5),
DATEADD(
MINUTE,
[duration],
CAST(LEFT([time], 2) + ':' + RIGHT([time], 2) AS DATETIME)
),
8
),
':',
''
)
Select left(New_Time,2)+RIGHT(New_Time,2)
from (
Select
LEFT(
cast(CONVERT ( time ,
dateadd(minute, duration, --Dateadd will add the minutes to the time given.
Cast(LEFT(mil_time,2)+':'+Right(mil_time,2) as time) --This transforms the varchar into a Time format SQL recognizes.
),
8) as varchar),5)
as New_Time
from (
select '2145' as mil_time, 200 as duration --This is the original data.
) Orig_tbl
) Time_Format