路径正确时,OPENJSON()SQL SERVER返回null

时间:2020-09-18 21:28:28

标签: json sql-server null open-json

这是我声明的json:

DECLARE @json VARCHAR(MAX) = N'
[
 {
  "mTruckId": -35839339,
  "mPositionId": 68841545,
  "mPositionDateGmt": "laboris ipsum ullamco",
  "mLatitude": -36598160.205007434,
  "mLongitude": 54707169.834195435,
  "mGpsValid": false,
  "mHeading": 114,
  "mSpeed": -888256.4982997179,
  "mAdditionalInformation": {
   "mVin": "voluptate veniam",
   "mOdometer": 25567959.615529776,
   "mEngineHours": -87509827.08880372,
   "mTemperatureSensors": [
    {
     "mUnit": "C",
     "mLabel": "aute in",
     "mValue": -74579140.64111689
    },
    {
     "mUnit": "C",
     "mLabel": "ullamco labore dolore",
     "mValue": -91870052.84894001
    }
   ]
  }
 },
 {
  "mTruckId": 80761376,
  "mPositionId": 88380593,
  "mPositionDateGmt": "sed pariatur ut sint",
  "mLatitude": 62504812.42302373,
  "mLongitude": 14622406.17103973,
  "mGpsValid": false,
  "mHeading": 302,
  "mSpeed": 39030054.634676635,
  "mAdditionalInformation": {
   "mVin": "aute",
   "mOdometer": 74400412.05641022,
   "mEngineHours": 88453976.08453897,
   "mTemperatureSensors": [
    {
     "mUnit": "F",
     "mLabel": "reprehenderit consectetur id ipsum",
     "mValue": 22634605.53841141
    },
    {
     "mUnit": "C",
     "mLabel": "magna consectetur esse",
     "mValue": 72633803.44269562
    }
   ]
  }
 }
]'

这是我的代码,用于从json中提取温度传感器数据。我认为这样做会成功,因为获取温度传感器数据的json层次结构是root-> mAdditionalInformation-> mTemperatureSensors。

SELECT  Unit,
        Label,
        Value
FROM OPENJSON(@json)
WITH(
    Unit    VARCHAR(15) '$.mAdditionalInformation.mTemperatureSensors.mUnit',
    Label   VARCHAR(50) '$.mAdditionalInformation.mTemperatureSensors.mLabel',
    Value   FLOAT       '$.mAdditionalInformation.mTemperatureSensors.mValue'
)

它返回两行均为空的行,为什么这样做呢?我希望它能够提取mTemperatureSensors数据中的每个元素。

Unit    Label   Value
NULL    NULL    NULL
NULL    NULL    NULL

2 个答案:

答案 0 :(得分:0)

select s.*
from openjson(@json)
with
(
    mTemperatureSensors nvarchar(max) '$.mAdditionalInformation.mTemperatureSensors' as json
) as t
cross/*outer*/ apply openjson(t.mTemperatureSensors)
with
(
mLabel nvarchar(20)
) as s

答案 1 :(得分:0)

@json 的内容插入到表格中之后,一个选项是逐步应用OPENJSONCROSS APPLY({{ 1}}):

tab

Demo

或根据您的情况声明标量变量 @json

SELECT  Unit, Label, Value
  FROM tab
 CROSS APPLY OPENJSON(JsonData)
             WITH (
                    TempSens NVARCHAR(MAX) '$.mAdditionalInformation.mTemperatureSensors' AS JSON ) Q1 
 CROSS APPLY OPENJSON (Q1.TempSens) 
             WITH (
                    Unit   NVARCHAR(MAX) '$.mUnit',
                    Label  NVARCHAR(MAX) '$.mLabel',
                    Value  FLOAT         '$.mValue'
                  ) Q2    

Demo