How to do Where clause on simple Json Array in SQL Server 2017?

柔情痞子 提交于 2019-12-25 03:20:29

问题


Say I have a column in my database called attributes which has this value as an example:

  {"pages":["Page1"]}

How can I do a where clause so I can filter down rows that have "Page1" in it.

  select JSON_QUERY(Attributes, '$.pages') 
  from Table
  where JSON_QUERY(Attributes, '$.pages') in ('Page1')

Edit:

From the docs it seems like this might work though it seems so complicated for what it is doing.

  select count(*)
  from T c
  cross apply Openjson(c.Attributes)
              with (pages nvarchar(max) '$.pages' as json) 
  outer apply openjson(pages) 
              with ([page] nvarchar(100) '$')
  where [page] = 'Page1'

回答1:


Something like this:

use tempdb
create table T(id int, Attributes nvarchar(max))

insert into T(id,Attributes) values (1, '{"pages":["Page1"]}')
insert into T(id,Attributes) values (2, '{"pages":["Page3","Page4"]}')
insert into T(id,Attributes) values (3, '{"pages":["Page3","Page1"]}')

select *
from T
where exists
( 
  select * 
  from openjson(T.Attributes,'$.pages') 
  where value = 'Page1'
)

returns

id          Attributes
----------- ---------------------------
1           {"pages":["Page1"]}
3           {"pages":["Page3","Page1"]}

(2 rows affected)


来源:https://stackoverflow.com/questions/54014774/how-to-do-where-clause-on-simple-json-array-in-sql-server-2017

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!