Adding Minutes to Date & Time in VARCHAR Data Type (SQL Server)

Rajender SinghRajender Singh
1 min read

Today while working in one of my Data Migration project I came up with this problem where Date & Time data was in varchar format and I need to add minutes ( if more than 180 minute then settle for 30min) to it and spit it out as varchar in DD/MM/YYYY HH24:MI:SS format.

After lot of brain storming mainly to satisfy myself, I settle on following idea.

SELECT 
TRAKDate,
TRAKStartTime,
TRAKEndTime,
CONVERT (VARCHAR, DATEADD(mi, 30, CONVERT(datetime, TRAKDate+' '+TRAKStartTime)),103)
+' '+ CASE 
    WHEN CAST(TRAKEndTime AS INT) < 181 THEN
        CONVERT (VARCHAR, DATEADD(mi, CAST(TRAKEndTime AS INT), CONVERT(datetime, TRAKDate+' '+TRAKStartTime)),8)
    ELSE CONVERT (VARCHAR, DATEADD(mi, 30, CONVERT(datetime, TRAKDate+' '+TRAKStartTime)),8) 
END finaldate
from rawdata.Appointment

Results:

Result Rows

More Rows

More Rows

It worked well for me and I hope it will help somebody :)

0
Subscribe to my newsletter

Read articles from Rajender Singh directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Rajender Singh
Rajender Singh