Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

datetime conversion fails in OPENJSON function

I am using a json coming from logicapp events which has datetime properties in below format

"startTime": "2017-07-12T17:14:16.0500772Z",
"endTime": "2017-07-12T17:14:17.2939322Z",

in a stored proc with the OPENJSON Sql function. When I execute the 'SELECT' with this function it fails with this error

Msg 241, Level 16, State 1, Line 33 Conversion failed when converting date and/or time from character string.

My observation has been that OPENJSON fails to convert the millisec part after the 3rd digit.

Question Has anyone seen such a problem with OPENJSON SQL function?

like image 520
TusharJ Avatar asked Jul 19 '17 16:07

TusharJ


People also ask

How do I fix conversion failed when converting date and or time from character string?

The way to solve this is to use the (slightly adapted) ISO-8601 date format that is supported by SQL Server - this format works always - regardless of your SQL Server language and dateformat settings.

How do you fix the conversion of a varchar data type to a datetime data type resulted in an out of range value?

The conversion of a varchar data type to a datetime data type resulted in an out-of-range value. You need separators for the date like a “/”, a “.” or a “-“. We use substring to concatenate the “-” to use an acceptable date format and then we use the CONVERT function to convert the characters to sql date.

What is SQL Server Openjson?

OPENJSON is a table-valued function that parses JSON text and returns objects and properties from the JSON input as rows and columns. In other words, OPENJSON provides a rowset view over a JSON document. You can explicitly specify the columns in the rowset and the JSON property paths used to populate the columns.


1 Answers

If DateTime2, you should have no issue

Example

select AsDT2 = try_convert(datetime2,'2017-07-12T17:14:16.0500772Z')
      ,AsDT  = try_convert(datetime, '2017-07-12T17:14:16.0500772Z')

Returns

AsDT2                         AsDT
2017-07-12 17:14:16.0500772   NULL   --<< Fails DateTime conversion

The Actual Conversion

Declare @JSON varchar(max) = '{"startTime": "2017-07-12T17:14:16.0500772Z","endTime": "2017-07-12T17:14:17.2939322Z"}'

SELECT * FROM  
 OPENJSON (@JSON )  
WITH (   
              startTime  datetime2 '$.startTime',  
              endTime    datetime2 '$.endTime'
 ) 

See It In Action dbFiddle

like image 63
John Cappelletti Avatar answered Sep 28 '22 16:09

John Cappelletti