4

I have a table which the 'Preference' column stores JSON strings.

a) I would like to get the type from companytype as rows. In my attempt on sqlfiddle I get the five rows but no data in them.

SELECT z.[Type]
FROM FinPreferences p
CROSS APPLY OPENJSON(Preference,'$.companytype.type') WITH (
    [Type] INT
) z
WHERE PreferenceID=1

b) How can I get the results as one string row i.e

1,2,3,4,5

This is the data inside the Preference column

   {
    "companysize":{"min":0,"max":5},
    "distance":{"min":100,"max":200},
    "companytype":{"type":[1,2,3,4,5]},
    "budget":{"min":1000,"max":2000}
    }

Fiddle is here

3
  • Post the table schema, queries in the question itself. Commented Oct 1, 2018 at 9:48
  • 1
    you can use JSON_QUERY Commented Oct 1, 2018 at 10:00
  • @ManojNaik there's nothing wrong with OPENJSON. JSON_QUERY won't return a rowset either Commented Oct 1, 2018 at 10:03

1 Answer 1

7

Either remove the WITH clause and use the value field to retrieve the array's values, eg:

SELECT z.value as Type
FROM FinPreferences p
CROSS APPLY OPENJSON(Preference,'$.companytype.type') z
WHERE PreferenceID=1

Or use just $ as the path in the WITH clause :

SELECT z.Type
FROM FinPreferences p
CROSS APPLY OPENJSON(Preference,'$.companytype.type') 
            WITH ( Type int '$') z
WHERE PreferenceID=1

WITH applies to the results returned by OPENJSON. The path $.companytype.type is just an array of integers, it doesn't have any other attributes

Sign up to request clarification or add additional context in comments.

3 Comments

This works. How would I get the results as one result such as 1,2,3,4,5 which is the part B?
Tried this but I get no values: SELECT JSON_VALUE( Preference, '$.companytype.type' ) AS [Type] FROM FinPreferences p WHERE p.PreferenceID=1
@alwaysVBNET that's a different question. JSON_VALUE returns scalar values, eg JSON_VALUE( Preference, '$.companytype.type[1]' ) will return 2. You need JSON_QUERY if you expect to return multiple values, like the contents of an array, eg JSON_QUERY( Preference, '$.companytype.type' ) will return [1,2,3,4,5]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.