Converting a varchar to datetime

  • I am trying to convert a varchar(255) column to datetime.  The varchar column has a date in the form of DD/MM/YYYY.  I created a new datetime column to receive the results. 

    update Inventory

    set DateColumn = convert(datetime, DateStringColumn, 101)

    This is complicated by the fact that DataStringColumn contains some bad values. 

    Any suggestions would be appreciated.

    David

     

  • Update Inventory

    set DateColumn = CASE WHEN ISDATE(DateStringColumn) = 1 THEN convert(datetime, DateStringColumn, 101) ELSE NULL END

  • Remi,

    Thank you.  Worked perfectly.

    David

     

  • Not to piddle, but this will perform better.

    update Inventory

    set DateColumn = convert(datetime, DateStringColumn, 101)

    where isdate(DateStringColumn) = 1

    Signature is NULL

  • While we're at it why not get rid of the convert statement it seems to work fine for me without it.

    update Inventory

    set DateColumn =  DateStringColumn

    where isdate(DateStringColumn) = 1

     

  • Thanks All...

    But isn't the explicit cast more efficient than the implicit cast? I'm not sure how SQLServer does it, but somehow it must find out the datatype that is being cast to a date. 

    David

     

  • Can't say that I know for sure which is the most efficient but if I were to explicity convert to datetime in this type of situation, I would not bother to convert it to a style (i.e. 101) as that seems irrelevant since it will not be stored in database that format anyway.

    I might use:

    update Inventory

    set DateColumn =  cast(DateStringColumn as datetime)

    where isdate(DateStringColumn) = 1

     

Viewing 7 posts - 1 through 6 (of 6 total)

You must be logged in to reply to this topic. Login to reply