Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Calculate time difference in SQL

We have two columns in SQL. one is total_work_time & next is total_exeption_time & both column data type is varchar

total_work_time value is 07:15:00

total_exeption_time value is 01:15:00

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

So I need to subtract total_work_timetotal_exeption_time and the result will be 06:00:00.

I have tried with concat(DATEDIFF(HOUR,total_exeption_time,total_work_time),':', DATEDIFF(MINUTE,total_exeption_time,total_work_time))

But the result is 6:360. from this, 360 is the problem, it taken total minutes. I need the result structure like 06:00:00. How to fix this issue using SQL Server.

>Solution :

You should be storing time values in a TIME datatype – using the correct datatype is not only a best practice but will reduce the problems you face in future.

You can convert your VARCHAR values to TIME and then use the following calculation which takes the difference in seconds (your lowest unit of interest one assumes) and creates a new TIME result.

DECLARE @total_work_time TIME = '07:15:00', @total_exeption_time TIME = '01:15:00';

SELECT CONVERT(TIME, DATEADD(SECOND, DATEDIFF(SECOND, @total_exeption_time, @total_work_time), '00:00'));
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading