1

I have an object in a database which I believe can be parsed using OPENJSON. If there is a better solution, I am definitely open to it. The values below are fictional.

TABLE

 DROP TABLE IF EXISTS #temp;
CREATE TABLE #temp (
ID INT,
Object VARCHAR(MAX)
);

INSERT INTO #temp
(
    ID,
    Object
)
VALUES
(   1, '{   "Country": "US",   "CountryName": "United States of America",   "Inflation": 5.0 }'),
(   2, '{   "Country": "MX",   "CountryName": "Mexico",   "Inflation": 6.0 }'),
(   3, '{   "Country": "CA",   "CountryName": "Canada,   "Inflation": 5.5 }');

ATTEMPTED SOLUTION

SELECT *
  FROM OPENJSON((SELECT Object FROM #temp))
  WITH (
         Country CHAR(2) '$.Country',
         CountryName VARCHAR(MAX) '$.CountryName',
         Inflation DECIMAL(2,1) '$.Inflation'
       )     

RESULT

Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.

DESIRED RESULT

ID Country Country Name Inflation
1 US United States of America 5.0
2 MX Mexico 6.0
1 CA Canada 5.5

Any assistance would be greatly appreciated!

1 Answer 1

1

After you add the " after Canada ... Use a CROSS APPLY

Select A.ID 
      ,B.*
 From  #temp A
 Cross Apply (
            SELECT *
              FROM OPENJSON(Object)
              WITH (
                     Country CHAR(2) '$.Country',
                     CountryName VARCHAR(MAX) '$.CountryName',
                     Inflation DECIMAL(2,1) '$.Inflation'
                   )     
             ) B

Results

enter image description here

EDIT

OR - If your JSON is that simple, the following is a nudge more performant.

 Select A.ID 
      ,Country     = JSON_VALUE(Object,'$.Country')
      ,CountryName = JSON_VALUE(Object,'$.CountryName')
      ,Inflation   = JSON_VALUE(Object,'$.Inflation')
 From  #Temp A
1
  • This is great! I believe this did the trick! Commented Jun 2, 2022 at 0:09

Not the answer you're looking for? Browse other questions tagged or ask your own question.