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