【问题标题】:TSQL How do i check array is a subset using JSON_QUERYTSQL我如何检查数组是使用JSON_QUERY的子集
【发布时间】:2020-05-22 19:36:57
【问题描述】:

我有以下表格Documents,其中数据以 JSON 格式存储。

DocumentID     Status        Data
------------------------------------------
1              Active        '{ "AccountNumber":["A1","A2","A3","A4"] }'
2              Active        '{ "AccountNumber":["A1","A3"] }'
3              Active        '{ "AccountNumber":["A2","A4"] }'
4              Active        '{ "AccountNumber":["A1"] }'

然后我有过滤器,它也是一个 json

 DECLARE @filter = '{ "AccountNumber":["A2","A3"] }'

如何在 where 子句中应用过滤器。

预期的结果应该返回匹配的文档,DocumentID 1,2,3

SELECT DocumentID 
FROM Documents D
WHERE
JSON_QUERY(D.Data,'$.AccountNumber') IN JSON_QUERY($(@filter,'$.AccountNumber') -- This is not working

【问题讨论】:

    标签: sql-server tsql json-query json-value


    【解决方案1】:
    select DocumentID
    from
      Documents D
    where
      exists (select value from openjson(D.data, '$.AccountNumber')
              intersect
              select value from openjson(@filter, '$.AccountNumber')
             )
    ;
    
    select distinct DocumentID
    from
      Documents D
      cross apply openjson(D.data, '$.AccountNumber') j
      inner join openjson(@filter, '$.AccountNumber') f on j.value = f.value
    ;
    

    【讨论】:

    • Json 比较不是 TypeSafe 吗?这意味着如果我已将 AccountNumber 作为整数数组 [111,222,333] 存储在 DB 中,但如果过滤器是字符串数组 ['111','222'] 它仍然会找到匹配的记录。 (反之亦然)
    • @LP13 这与 json 无关。当它将 json 解包成列时,应用正常的 SQL Server 规则,并且根据data type precedence,在将 varchars 与 ints 进行比较时,它们首先转换为 ints。
    • @LP13 OPENJSON() 具有默认架构(没有 WITH 子句)returns 具有列 keyvaluetype 的表和 value 列是nvarchar(max) 专栏。因此,两个调用(SELECT [value] FROM OPENJSON('["111","222"]')SELECT [value] FROM OPENJSON('[111,222]')都将 AccountNumber 作为 nvarchar 列返回。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-13
    • 2012-05-13
    • 2010-09-24
    • 1970-01-01
    • 2020-03-10
    相关资源
    最近更新 更多