简体   繁体   中英

Adding time(hh:mm:ss) to a datetime field in SQL

I want to add the run_duration column(hh:mm:ss) to the run_datetime(datetime) column to calculate the endtime by using the following query:

SELECT checkdate, run_datetime, run_duration,
cast(run_datetime as datetime) + cast(run_duration as datetime) as readytime, 
cast(cast(run_datetime as datetime) + cast(run_duration as datetime) as datetime) as readytime_datetime
FROM table

The problem is that it is not adding up correctly for some records because it is summing above the 60 seconds:

在此处输入图片说明

Is there another way to do this correctly?

Use MySQL's built-in addtime() function instead of the + operator:

SELECT checkdate,
       run_datetime,
       run_duration,
       addtime(cast(run_datetime as datetime), cast(run_duration as time)) as readytime
FROM table

The + operator converts the datetimes to numbers and adds them up as such.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM