T-SQL:查询JSON列中数组元素缺少值的记录

ryoqjall  于 2023-10-21  发布在  其他
关注(0)|答案(1)|浏览(114)

在SQL Server 2016中,我有一个像这样的Shipments表:

create table Shipments 
(
    shipment_number varchar(20),
    shipment_json nvarchar(MAX)
);

shipment_json列内容如下:

{
    "shipmentNumber": "008863",
    "stops": [
        {
            "locations": [
                {
                    "stopRole": "originPort",
                    "closeDateTime": "2023-08-22T05:00:00"
                },
                {
                    "stopRole": "destinationPort"
                }
            ]
        }
    ]
}

现在,我需要一个SELECT查询记录,其中在“locations”数组中,“location”元素中的stopRole =“destinationPort”missing closeDateTime值。上面的json示例就是一个例子。
我很感激任何帮助。

s5a0g9ez

s5a0g9ez1#

使用openjsoncross apply可以将stopRole和closeDateTime视为典型列,例如:

SELECT
      shipment_number
    , stopRole
    , closeDateTime
FROM Shipments
CROSS APPLY OPENJSON(shipment_json, '$.stops')
    WITH (
        locations nvarchar(MAX) '$.locations' AS JSON
    ) AS Stops
CROSS APPLY OPENJSON(Stops.locations)
    WITH (
        stopRole nvarchar(50) '$.stopRole',
        closeDateTime nvarchar(50) '$.closeDateTime'
    ) AS Locations
WHERE Locations.closeDateTime IS NULL

| 装运编号|stopRole|关闭日期时间|
| --|--|--|
| 008863 |目的地端口| * 空 *|
fiddle

相关问题