Adding Time in HH:MM Format – Useful SQL Query (Alternate solution)


I came across this post “Adding Time in HH:MM Format – Useful SQL Query” from codeproject website http://www.codeproject.com/Tips/207655/Adding-Time-in-HH-MM-Format-Useful-SQL-Query.
Here is a simple version I would like to recommend:

SELECT CONVERT(VARCHAR(5),
CAST(DATEADD(s,SUM(DATEDIFF(s,0,CAST(timeduration as DATETIME))),0) as DateTIME)
–Format to hh:mi:ss:mmm(24h)
, 114) AS timeSum
FROM mytable
The table and sample data (loaded for SQL Server 2008)
–CREATE TABLE mytable
–(
–id int identity(1,1),
–timeduration varchar(5),
–mytime time(0)
–)
If you are using SQL Server 2008 or above, you can use time data type directly.
SELECT CAST(dateadd(minute,sum(datediff(minute,0,mytime)),
Cast(CONVERT(VARCHAR(10), Getdate(), 101) AS DATETIME)) as Time(0))
FROM mytable

Advertisements


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s