Search code examples
sql-serverdatetimeconvertersvarchar

converting a varchar to datetime in sql server


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?


Solution

  • 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.