I have a nvarchar(1000) field in my table and I am storing JSON data in that column.
eg :
CONTENT_RULE_ID CONTENT_RULE
1 {"EntityType":"Inquiry", "Values":[1,2]}
2 {"EntityType":"Inquiry", "Values":[1,3]}
3 {"EntityType":"Inquiry", "Values":[2,4]}
4 {"EntityType":"Inquiry", "Values":[5,6,1]}
6 {"EntityType":"Inquiry", "Values":[8,1]}
8 {"EntityType":"Inquiry", "Values":[10,12,11]}
from this how can I get all the CONTENT_RULE_ID which is having inquiry id 1 using JSON_QUERY in sql server
@Harisyam, could you please try following query
declare @val int = 1
;with cte as (
select *
from CONTENT_RULES
cross apply openjson (CONTENT_RULE, '$')
), list as (
select
CONTENT_RULE_ID, replace(replace([value],'[',''),']','') as [value]
from cte
where CONTENT_RULE_ID in (
select CONTENT_RULE_ID
from cte
where [key] = 'EntityType' and [value] = 'Inquiry'
)
and [key] = 'Values'
)
select
CONTENT_RULE_ID, s.value
from list
cross apply string_split([value],',') s
where s.value = @val
I used SQL string_split function to get inquiry values one by one
output is
A second query can be following one
select
CONTENT_RULE_ID
from CONTENT_RULES
cross apply openjson (CONTENT_RULE, '$')
where replace(replace(value,'[',','),']',',') like '%,1,%'
And maybe the most complete SQL query which requires OpenJSON support is as follows
select
content_rule_id,
[value]
from Content as c
cross apply openjson(c.CONTENT_RULE, '$') with (
EntityType nvarchar(100),
[Values] nvarchar(max) as json
) as e
cross apply openjson([Values], '$') as v