SQL Server CAST/CONVERT Varchar TIME "53:15:00" to TIME format in DB?


I need to convert a varchar field of data from Varchar to TIME.

What is the easiest syntax to use?
LVL 17
MIKESoftware Solutions ConsultantAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Jim HornMicrosoft SQL Server Data DudeCommented:
Not possible, as time ranges from 00:00 to 23:59:59.999, so 'two days and 05:15' is not convertible to a TIME format.  

Tell us what you're trying to pull off, and maybe we can suggest a workaround.
MIKESoftware Solutions ConsultantAuthor Commented:
Sorry for confusion, I need to convert this to time format:

insert into Table1
select '23:59:59.999'

The FieldType in DB is Time(0)
Jim HornMicrosoft SQL Server Data DudeCommented:
This works on my 2012 box.
Replace the (0) with the decimal number of seconds needed.
CREATE TABLE #t (t time(0)) 

insert into #t (t)


Open in new window

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Scott PletcherSenior DBACommented:
You'll have to strip whole days off to make it a valid time.  Date/days are not stored in a time column anyway.

--INSERT INTO destination_table ( col_name, ... )
    SELECT '53:15:00' AS varchar_time UNION ALL
    SELECT '23:59:59.997' UNION ALL
    SELECT '9:23:11' UNION ALL
    SELECT '33'
) AS sample_source_data
    SELECT CAST(LEFT(varchar_time, CASE WHEN CHARINDEX(':', varchar_time) = 0 THEN LEN(varchar_time)
        ELSE CHARINDEX(':', varchar_time) - 1 END) AS int) AS varchar_time_hours
) AS assign_alias_names1
    SELECT CASE WHEN varchar_time_hours <= 23 THEN varchar_time ELSE STUFF(varchar_time, 1, LEN(varchar_time_hours),
        CAST(CAST(varchar_time_hours AS int) % 24 AS varchar(2))) END AS varchar_time_new
) AS assign_alias_names2
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Microsoft SQL Server

From novice to tech pro — start learning today.