How to convert a column of nvarchar string in hh:mm:ss format into datatype of time permanently in a table?

StackOverflow https://stackoverflow.com/questions/19630426

Question

I want to convert a table column like

Departure_time

06:44:00 (<- these are just NVARCHAR strings)

06:45:00

06:45:00

06:46:00

06:47:00

06:47:00

06:48:00

06:49:00

06:50:00

06:50:00

06:50:00

06:51:00

06:51:00

06:52:00

06:52:00

(sorry guys I really do want to post a screen-shot here which would made the post looks way much better but it says I need a reputation of 10. So, I just make one table column)

which in NVARCHAR datatype, into TIME type in MSSQL 2012?

I tried Time(0) and Time(7) and all threw an error of

"Conversion failed when converting date and/or time from character string."

and I do want to change the type of that column of the table permanently. Not only select them and present them in the time format.

So... anyone can help me on how to do this please?

Thank you!

Was it helpful?

Solution

The following works as (I) would expect and ends up with a table consisting of a single time(7) column:

create table T (Departure_time nvarchar(10) not null)
insert into T(Departure_time) values
('06:44:00'),('06:45:00'),('06:45:00'),('06:46:00'),('06:47:00'),
('06:47:00'),('06:48:00'),('06:49:00'),('06:50:00'),('06:50:00'),
('06:50:00'),('06:51:00'),('06:51:00'),('06:52:00'),('06:52:00')

alter table T alter column Departure_Time time(7) not null

I suspect you have some rows which don't have valid values in them. These may be more or less easy to discover, depending on how close to the required format the invalid values are.

select * from t where not Departure_time like '[0-2][0-9]:[0-5][0-9]:[0-5][0-9]'

Finds values that are definitely wrong. But it wouldn't find e.g. 27:34:32

OTHER TIPS

The solution is very simple:

select cast (Departure_time as time) from <you_table>
select convert(varchar(32),getdate(),8)

OR

DECLARE @DateNow smalldatetime
SET @DateNow = GETDATE()

SELECT CONVERT(CHAR(5), @DateNow, 8) 

OR

 UPDATE your_tablename
    SET columnName = CONVERT(NVARCHAR(255),CONVERT(SMALLDATETIME, columnName,105))
    ALTER TABLE myTable
    ALTER COLUMN columnName SMALLDATETIME
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top