Question

I have a varchar 20130909132512 and I would like to convert it into just a date 2013-09-09

I keep getting an error when trying

select convert(datetime,'20130909132512',105)

and I am trying to avoid using

select convert(datetime,SUBSTRING('20130909132512',0,8),105)

if possible. Any ideas on how I can do this?

Was it helpful?

Solution 2

Whether you use bummi's STUFF method or continue using SUBSTRING, you're going to have to pre-format the string no matter what you do.

In this case, SUBSTRING will perform a bit faster

SELECT CONVERT(date, SUBSTRING('20130909132512', 0, 9), 20)

You'll want to use "20" as the conversion style, though, if you want the date in the format 2013-09-09.

OTHER TIPS

You could transform your varchar to 20130909 13:25:12 using STUFF

Declare @a Varchar(20)
Select @a = '20130909132512'
select convert(datetime,
              STUFF(STUFF(STUFF(@a,13,0,':'),11,0,':'),9,0,' ')
              ,105)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top