I am writing a SQL query to convert string to datetime:
SELECT CAST('2017-04-07.15-23-44' AS datetime)
When I am converting it to datetime getting an error
varchar data type to datetime data type resulted in out of range value.
I am writing a SQL query to convert string to datetime:
SELECT CAST('2017-04-07.15-23-44' AS datetime)
When I am converting it to datetime getting an error
varchar data type to datetime data type resulted in out of range value.
Split the string with the . as delimiter and in the 2nd part replace all '-' with ':'.
Concatenate the 2 parts again and then cast it to DATETIME:
DECLARE @d VARCHAR(20) = '2017-04-07.15-23-44';
SELECT CAST(LEFT(@d, CHARINDEX('.', @d) - 1) + ' ' +
REPLACE(SUBSTRING(@d, CHARINDEX('.', @d) + 1, LEN(@d)), '-', ':')
AS datetime
)
See the demo.