【问题标题】:How to get complex JSON string into columns SQL Server如何将复杂的 JSON 字符串放入 SQL Server 列中
【发布时间】:2021-04-22 14:30:02
【问题描述】:

我已将一些数据作为 JSON 字符串存储在表中,如下所示。

[
   {
      "firstName":"John",
      "lastName":"Smith",
      "age":25,
      "Address":{
         "streetAddress":"21 2nd Street",
         "city":"New York",
         "state":"NY",
         "postalCode":"10021"
      },
      "PhoneNumbers":{
         "home":"212 555-1234",
         "fax":"646 555-4567"
      }
   },
   {
      "firstName":"Mike",
      "lastName":"Lee",
      "age":30,
      "Address":{
         "streetAddress":"10 Street",
         "city":"New York",
         "state":"NY",
         "postalCode":"10021"
      },
      "PhoneNumbers":{
         "home":"212 555-3265",
         "fax":""
      }
   }
]

要将这些数据导出到 excel 文件,我需要进行查询以获取这些详细信息,如下所示

使用 CROSS APPLY OPENJSON 我可以获取姓名和年龄,但如何获取地址和联系方式作为列?

【问题讨论】:

    标签: json sql-server cross-apply open-json


    【解决方案1】:

    您需要使用OPENJSON() 和相应的paths:

    JSON:

    DECLARE @json nvarchar(max) = N'[
       {
          "firstName":"John",
          "lastName":"Smith",
          "age":25,
          "Address":{
             "streetAddress":"21 2nd Street",
             "city":"New York",
             "state":"NY",
             "postalCode":"10021"
          },
          "PhoneNumbers":{
             "home":"212 555-1234",
             "fax":"646 555-4567"
          }
       },
       {
          "firstName":"Mike",
          "lastName":"Lee",
          "age":30,
          "Address":{
             "streetAddress":"10 Street",
             "city":"New York",
             "state":"NY",
             "postalCode":"10021"
          },
          "PhoneNumbers":{
             "home":"212 555-3265",
             "fax":""
          }
       }
    ]'
    

    声明:

    SELECT *
    FROM OPENJSON(@json) WITH (
       FirstName nvarchar(100) '$.firstName',
       LastName nvarchar(100) '$.lastName',
       Age int '$.age',
       Name nvarchar(100) '$.firstName',
       StreetAddress nvarchar(100) '$.Address.streetAddress',
       City nvarchar(100) '$.Address.city',
       State nvarchar(100) '$.Address.state',
       PostalCode nvarchar(100) '$.Address.postalCode',
       HomePhone nvarchar(100) '$.PhoneNumbers.home',
       Fax nvarchar(100) '$.PhoneNumbers.fax'
    )
    

    结果:

    FirstName LastName Age Name StreetAddress City     State PostalCode HomePhone    Fax
    John      Smith     25 John 21 2nd Street New York NY    10021      212 555-1234 646 555-4567
    Mike      Lee       30 Mike 10 Street     New York NY    10021      212 555-3265    
    

    【讨论】:

    • 谢谢。我很接近,只是缺少 Address.postalCode 的东西。 :)
    猜你喜欢
    • 2017-03-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-20
    • 2021-02-05
    • 1970-01-01
    相关资源
    最近更新 更多