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
JSON functions, first introduced in SQL Server 2016, enable you to combine NoSQL and relational concepts in the same database.
SELECT c.*
FROM CONTENT_RULES AS c
CROSS APPLY OPENJSON(JSON_QUERY(content_rule, '$')) AS x
CROSS APPLY OPENJSON(x.[Value], '$') AS y
where x.[key]='Values' and y.[value]=1
@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
My case is similar but instead of an integer array, mine is an array of complex type. Here is my code based on David Browne's solution
SELECT *
FROM TableName AS T
WHERE EXISTS
(
SELECT *
FROM OPENJSON(T.JsonColumn, '$.Details')
WITH
(
OrderNumber VARCHAR(200) '$.OrderNumber',
Quantity INT '$.Quantity'
)
WHERE OrderNumber = '1234567'
);
In your case:
SELECT C.*
FROM CONTENT_RULES AS C
WHERE EXISTS
(
SELECT *
FROM OPENJSON(C.CONTENT_RULE, '$.Values')
WHERE value = 1
);
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