Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/80.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/json/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql 按JSON列中的值搜索_Sql_Json_Sql Server - Fatal编程技术网

Sql 按JSON列中的值搜索

Sql 按JSON列中的值搜索,sql,json,sql-server,Sql,Json,Sql Server,我有一个表,其中包含带有JSON值的列,例如: 身份证件 价值 1. {“组件”:[{“标签”:“问候语1”,“组件”:[{“标签”:“你好”,“值”:10},{“标签”:“你好”,“值”:20}]} 2. {“组件”:[{“标签”:“问候语2”,“组件”:[{“标签”:“aloha”,“值”:30},{“标签”:“hola”,“值”:40}]} 因为有许多层嵌套的JSON对象,所以需要向SQL Server指定需要挖掘所有这些层的内容。每个层都有标签和组件属性,这增加了(可能是不必要的)复杂性

我有一个表,其中包含带有JSON值的列,例如:

身份证件 价值 1. {“组件”:[{“标签”:“问候语1”,“组件”:[{“标签”:“你好”,“值”:10},{“标签”:“你好”,“值”:20}]} 2. {“组件”:[{“标签”:“问候语2”,“组件”:[{“标签”:“aloha”,“值”:30},{“标签”:“hola”,“值”:40}]}
因为有许多层嵌套的JSON对象,所以需要向SQL Server指定需要挖掘所有这些层的内容。每个层都有
标签
组件
属性,这增加了(可能是不必要的)复杂性,也需要处理。在您的“简化JSON”示例中,需要查询5个层,注意在适当的级别应用过滤器,以确保返回所有嵌套属性

可以说,这并不理想,而且可以从一个不太复杂的JSON模式中获益匪浅

查询
输出 招呼 欢迎标签 欢迎值 问候1 你好 10
你试过什么?你在哪里卡住了?向我们展示您的尝试。使用类似于的
?JSON在一天结束时只是一个
nvarchar
。到目前为止,我发现的所有示例实际上都只是在一些简单的json中进行搜索。您能够更改json的格式吗?我不明白,如果在数据中保持一致或在
问候语
数组中保留各种
问候语
值,为什么不使用
问候语1
问候语2
等值作为属性名?您的
标签
组件
设置使得这比感谢您所需要的困难得多!这正是我需要的!
declare @t table(id int,[value] nvarchar(1000));
insert into @t values
 (1,'{"components": [{"label": "greeting 1", "components": [{"label": "hello", "value": 10}, {"label":"hi", "value": 20}]}]}')
,(2,'{"components": [{"label": "greeting 2", "components": [{"label": "aloha", "value": 30}, {"label":"hola", "value": 40}]}]}')
;

select g.Greeting
      ,v.GreetingLabel
      ,v.GreetingValue
from @t as t
    cross apply openjson(t.[value],'$')
        with(Greetings nvarchar(max) 'strict $.components' as json) as j    -- Use of optional strict keyword requires that the property exists within the JSON object
    cross apply openjson(j.Greetings,'$')
        with(Greeting nvarchar(50) 'strict $.label'
            ,Components nvarchar(max) 'strict $.components' as json
            ) as g
    cross apply openjson(g.Components,'$')
        with(GreetingLabel nvarchar(50) 'strict $.label'
            ,GreetingValue int 'strict $.value'
            ) as v
where g.Greeting like 'greeting%'
    and v.GreetingValue = 10;