【问题标题】:How to do Where clause on simple Json Array in SQL Server 2017?如何在 SQL Server 2017 中对简单 Json 数组执行 Where 子句?
【发布时间】:2019-01-03 00:06:01
【问题描述】:

假设我的数据库中有一个名为 attributes 的列,它具有以下值作为示例:

  {"pages":["Page1"]}

如何创建 where 子句,以便过滤掉包含“Page1”的行。

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

编辑:

docs 看来,这似乎可行,尽管它的作用似乎很复杂。

  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'

【问题讨论】:

  • 而不是 in,你试过用 like 吗?我认为它提供了我们有第 1 页引用的实例(甚至不使用 Json_query),还有 Json_query 您是否尝试在那里提取值或选择列表中的 JSON 格式?

标签: json sql-server sql-server-2017


【解决方案1】:

类似这样的:

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'
)

返回

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

(2 rows affected)

【讨论】:

  • 好的,我会试试的。我还从我在 MS 文档上找到的示例中提出了上述内容,尽管我认为您的看起来更简单。
猜你喜欢
  • 1970-01-01
  • 2020-02-09
  • 1970-01-01
  • 1970-01-01
  • 2021-12-10
  • 2010-09-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多