如何从mssql中的json列获取数据

时间:2021-06-15 10:05:33

标签: sql json sql-server

我正在努力编写一个查询,该查询从具有某些特定条件的 json 列中获取值。我有一个名为 Table1 的表,其中有一列名为 Data 的 nvarchar(max) 类型,其中包含一些 json 值。 json 本身看起来像这样:

{
"Addresses": [
    {
        "ApartmentNumber": "1",
        "City": "Rome",
        "CountryCode": "IT",
        "HouseNumber": "2",
        "Post": "Rome",
        "PostalCode": "11-111",
        "Region": "Rome",
        "Street": "Italian",
        "StreetPrefix": "St.",
        "TypeCode": "PERMANENT"
    },
    {
        "ApartmentNumber": "11",
        "City": "Madrid",
        "CountryCode": "ES",
        "HouseNumber": "22",
        "Post": "Madrid",
        "PostalCode": "11-111",
        "Region": "Madrid",
        "Street": "Spanish",
        "StreetPrefix": "St.",
        "TypeCode": "CORRESPONDENCE"
    }
],
"Contacts": [
    {
        "TypeCode": "EMAIL",
        "DefaultContact": false,
        "Value": "sample@xyz.com"
    }
],
"PersonData": {
    "BirthDate": "1968-08-03T00:00:00",
    "CitizenshipCode": "US",
    "DeathDate": "0001-01-01T00:00:00",
    "FirstName": "John",
    "Gender": "M",
    "LastName": "Jones"
}

}

我想从 TypeCode 为“CORRESPONDENCE”的 Addresses 节点获取 CountryCode 的值。我试图通过 JSON_VALUE 和 JSON_QUERY 函数的组合来实现这一点,但我失败了。以下是我的一些试验示例:

查询:

SELECT JSON_QUERY(t.Data, '$.Addresses') AS Address FROM [Table1] t

结果:

[
{
    "ApartmentNumber": "1",
    "City": "Rome",
    "CountryCode": "IT",
    "HouseNumber": "2",
    "Post": "Rome",
    "PostalCode": "11-111",
    "Region": "Rome",
    "Street": "Italian",
    "StreetPrefix": "St.",
    "TypeCode": "PERMANENT"
},
{
    "ApartmentNumber": "11",
    "City": "Madrid",
    "CountryCode": "ES",
    "HouseNumber": "22",
    "Post": "Madrid",
    "PostalCode": "11-111",
    "Region": "Madrid",
    "Street": "Spanish",
    "StreetPrefix": "St.",
    "TypeCode": "CORRESPONDENCE"
}

]

或者这个:

查询:

 select top 1 JSON_VALUE(t.Data, '$.PersonData.LastName') FROM [Table1] t where ISJSON(t.Data) > 0 and JSON_VALUE(pd.BusinessPartner, '$.PersonData.Gender') = 'F'

结果: “琼斯”

但是当我用地址作为条件编写类似的查询时:

查询:

  select top 1 JSON_VALUE(t.Data, '$.Addresses.CountryCode') FROM [Table1] t where ISJSON(t.Data) > 0 and JSON_VALUE(t.Data,'$.Addresses.TypeCode') = 'CORRESPONDENCE'

结果是空字符串。

提前致谢

1 个答案:

答案 0 :(得分:0)

从 SQL Server 2016 开始,您可以查询 JSON 列。请参阅文档:Work with JSON data

对您来说有趣的部分是 Analyze JSON data with SQL queries

完成:

select Id, PostalCode
from Address
CROSS APPLY OPENJSON (Address.Data, N'$.Addresses')
WITH (
    TypeCode varchar(50) '$.TypeCode',
    PostalCode varchar(50) '$.PostalCode'
) AS AddressesJsonData
WHERE TypeCode  = N'PERMANENT'