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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With