Sql Server 2016中json数据的Where子句

时间:2018-01-12 10:17:38

标签: json sql-server sql-server-2016 json-query sql-server-json

我的表中有一个nvarchar(1000)字段,我将JSON数据存储在该列中。

例如:

 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]}

从这个如何在sql server中使用JSON_QUERY获取所有具有查询ID 1的CONTENT_RULE_ID

3 个答案:

答案 0 :(得分:4)

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

答案 1 :(得分:1)

@Harisyam,您可以尝试以下查询

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

我使用SQL string_split function逐个获取查询值

输出

enter image description here

第二个查询可以跟随一个

select
    CONTENT_RULE_ID
from CONTENT_RULES
cross apply openjson (CONTENT_RULE, '$')
where replace(replace(value,'[',','),']',',') like '%,1,%'

可能需要OpenJSON支持的最完整的SQL查询如下

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

答案 2 :(得分:0)

sql server 2016可以打开JSON。

试试这个:

SELECT c.content_rule_ID, y.[key], y.[value]
  FROM content_rules AS c
  CROSS APPLY OPENJSON(JSON_QUERY(content_rule, '$.content_rule')) AS x
  CROSS APPLY OPENJSON(x.[Values], '$') AS y
  where y.[value] = 1
    and x.[EntityType] = 'Inquiry';