查询json列中的键值

68bkxrlz  于 2023-01-03  发布在  其他
关注(0)|答案(1)|浏览(121)

我有一个表“jobs”,其中一列名为“check_list”(varchar(max),该列具有JSON值,示例值为

{
   "items":[
      {
         "name":"machine 1",
         "state":"",
         "comment":"",
         "isReleaseToProductionCheck":true,
         "mnachine_id":10
      },
      {
         "name":"machine 2",
         "state":"",
         "comment":"",
         "isReleaseToProductionCheck":true,
         "machine_id":12
      }
   ]
}

现在,我该如何编写SQL查询,以便只返回“check_list”列中包含[machine_id] = 12项的行

ifsvaxew

ifsvaxew1#

经过反复试验,最后这是适合我的解决方案,我不得不添加ISJSON检查,因为一些旧数据是无效的

WITH jobs (id, workorder, selectedMachine) AS(
  SELECT 
    [id], 
    [workorder], 
    (
      select 
        * 
      from 
        openjson(check_list, '$.items') with (machine_id int '$.machine_id') 
      where 
        machine_id = 12
    ) as selectedMachine 
  FROM 
    engineering_job_schedule 
  WHERE 
    ISJSON(check_list) > 0
) 
Select 
  * 
from 
  jobs 
where 
  selectedMachine = 12

相关问题