Zanam
Zanam

Reputation: 4807

Convert varchar to time

I have tried the links available here for similar questions before but it does not work. So I am posting my case here.

I have time in format:

09:47:11:895799

This is stored as varchar(50) in my Microsoft SQL Server database.

I am trying to convert it to time format as on this link.

hh:mm:ss[.nnnnnnn]

Can you please help?

Upvotes: 8

Views: 62555

Answers (2)

Kaf
Kaf

Reputation: 33809

You can also make your string as hh:mi:ss:mmm (24 hour format) and then convert as time. That means trimming out last 3 digits from your milli seconds without replacing last ':' with '.'

Here is MSDN link for more details of formatting. Here is working example of SQL Fiddle

DECLARE @s varchar(50) = '09:47:11:895799'
SELECT Convert(time, Left(@s,Len(@s)-3), 114)

Upvotes: 7

Martin Smith
Martin Smith

Reputation: 452957

The string is in the wrong format. It should be 09:47:11.895799. You need to replace the final : with a .

SELECT CAST(STUFF('09:47:11:895799', 9,1,'.') AS TIME)

Upvotes: 16

Related Questions