I have a string like this that I want to convert to a DATETIME value.
DECLARE @eh NVARCHAR(MAX) = '2021-07-19 14:00:39.0000000'
So this is what I tried:
DECLARE @eh NVARCHAR(MAX) = '2021-07-19 14:00:39.0000000'
SELECT CONVERT(DATETIME, @eh)
But it always returns this error:
Msg 241, Level 16, State 1, Line 3
Conversion failed when converting date and/or time from character string.
I am not sure what is special about the format of my string value that is causing the issue.
I tried the code above and I am using SQL Server.
>Solution :
You’re trying to convert the empty @time variable, not the string. Try SELECT CONVERT(DATETIME, @eh) instead.
With the current text you’ll get an error because the legacy datetime type doesn’t have nanosecond precision. If you include only milliseconds, it will work.
DECLARE @eh NVARCHAR(MAX) = '2021-07-19 14:00:39.000';
SELECT CONVERT(DATETIME, @eh);
---
2021-07-19 14:00:39.000
If you use datetime2 instead of datetime you can parse nanoseconds too:
DECLARE @eh NVARCHAR(MAX) = '2021-07-19 14:00:39.0000000'
SELECT CONVERT(DATETIME2, @eh)
---
2021-07-19 14:00:39.0000000