简体   繁体   中英

How to read JSON text from Sql Server 2016 table column

I have following JSon data in Sql Server.

{
 "PartnerName": null,
 "PartnerCurrencyCode": "UAD",
 "PricingConditions": [
  {
    "PricingConditionId": 659853,
    "ConditionTypeCode": "ABCD",
    "ConcessionItemTypeCode": "ABC",
    "PriceLevel": null
  }
],
"CurrencyMultiplier": 0
}

Expected Results is:

PartnerName  PartnerCode    PartnerCurrencyCode  PricingConditionId
NULL         NULL           UAD                   659853

I have read that Sql Server 2016 has the Capabilities of reading JSON Data and Tried with the following Queries.

Query 1:

SELECT * FROM OPENJSON(@json, '$')

Query 2:

SELECT *  
FROM OPENJSON(@json)  
WITH (PartnerName NVARCHAR(50) '$.PartnerName',
     PartnerCode nvarchar(50) '$.PartnerCode',
     PartnerCurrencyCode nvarchar(50) '$.PartnerCurrencyCode',
     PricingConditionId nvarchar(50)   '$.PricingConditions.PricingConditionId')

Query 2 Results:

PartnerName  PartnerCode    PartnerCurrencyCode  PricingConditionId
NULL         NULL           UAD                  NULL

I Was Expecting "PricingConditionId" Value is - 659853

Try this query:

SELECT PartnerName,
       PartnerCode,
       PartnerCurrencyCode,
       [PricingConditions[0]].PricingConditionId AS ProductID1
FROM OPENJSON (@json) 
WITH (
    PartnerName NVARCHAR(50),
    PartnerCode NVARCHAR(50),
    PartnerCurrencyCode NVARCHAR(50),
    [PricingConditions[0]].PricingConditionId NVARCHAR(50)
) AS Partners

Here is a link to a great article which discusses several approaches to handle your problem.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM