Converting varchar to datetime

  • ColdCoffee (3/14/2012)


    How about this?

    Sample data

    DECLARE @Table TABLE ( DatetimeasVC VARCHAR(30) );

    INSERT @Table

    SELECT '10/28/2011 11:47:55.686455 AM'

    UNION ALL

    SELECT '9/28/2011 11:47:55.123455 AM'

    UNION ALL

    SELECT '11/12/2011 11:47:55.789455 PM'

    UNION ALL

    SELECT '10/9/2011 11:47:55.9996 AM'

    UNION ALL

    SELECT '1/26/2011 11:47:55.3456 PM'

    UNION ALL

    SELECT '1/2/2012 11:47:55.2334455 PM'

    And the code:

    SELECT DatetimeasVC , CrsApp1.String , CONVERT( DATETIME , CrsApp1.String) [Converted To DateTime]

    FROM @Table

    CROSS APPLY (SELECT CHARINDEX('.',DatetimeasVC ) ) CrsApp (Idx)

    CROSS APPLY (SELECT LEFT ( DatetimeasVC , CrsApp.Idx + 3 ) + ' ' + RIGHT( DatetimeasVC , 2) ) CrsApp1 (String)

    Looks good to me. Now we just need to hear from the OP.

  • ColdCoffee (3/14/2012)


    How about this?

    SELECT DatetimeasVC , CrsApp1.String , CONVERT( DATETIME , CrsApp1.String) [Converted To DateTime]

    FROM @Table

    CROSS APPLY (SELECT CHARINDEX('.',DatetimeasVC ) ) CrsApp (Idx)

    CROSS APPLY (SELECT LEFT ( DatetimeasVC , CrsApp.Idx + 3 ) + ' ' + RIGHT( DatetimeasVC , 2) ) CrsApp1 (String)

    This fails when the string has zero or one decimal place(s). This code will work for those formats.

    SELECT DatetimeasVC , CrsApp1.String , CONVERT( DATETIME , CrsApp1.String) [Converted To DateTime]

    FROM @Table

    CROSS APPLY (SELECT PATINDEX('%.[0-9][0-9]%',DatetimeasVC ) ) CrsApp (Idx)

    CROSS APPLY (SELECT CASE WHEN CrsApp.Idx > 0 THEN LEFT ( DatetimeasVC , CrsApp.Idx + 3 ) + ' ' + RIGHT( DatetimeasVC , 2) ELSE DatetimeasVC END ) AS CrsApp1 (String)

    I replaced the CHARINDEX() with a PATINDEX() to make sure there were at least two digits after the decimal point and then used a CASE expression to return the original string if when there was no match for the PATINDEX().

    Drew

    J. Drew Allen
    Business Intelligence Analyst
    Philadelphia, PA

Viewing 2 posts - 16 through 16 (of 16 total)

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