Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

CONVERT function cannot convert string to DATETIME

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading