【问题标题】:Counting size of an array inside another JSON array: SQL SERVER计算另一个 JSON 数组中数组的大小:SQL SERVER
【发布时间】:2021-04-01 06:18:52
【问题描述】:

JSON 对象结构为:

{
  "store": {
    "storeId":123,
    "operations": {
      "seasons": [
        {
          "storeHours": [{},{},{}]  // consider it has 3 objects
        },
        {
          "storeHours": [{},{}]  //consider it has 2 objects
        }
      ]
    }
  }
}

我想计算"storeHours" 的大小。我试过了:

DECLARE @count INT = 0;
DECLARE @destination NVARCHAR = (N'$.store.operations.seasons[' +  @count +  N'].storeHours');

也尝试过:

DECLARE @destination NVARCHAR = CONCAT(N'$.store.operations.seasons[',  @count, N'].storeHours');

DECLARE @storeHoursCount INT = (
   select count(A.[key]) as [count] 
   from (VALUES(@json)) V(J)
   CROSS APPLY OPENJSON(V.J) WITH(
      [storeHours] nvarchar(MAX) @destination  AS JSON) S
   CROSS APPLY OPENJSON(S.storeHours) A
);

我收到一个错误:

“@destination”附近的语法不正确

这行得通:

DECLARE @storeHoursCount INT = (
   select count(A.[key]) as [count] 
   from (VALUES(@json)) V(J)
   CROSS APPLY OPENJSON(V.J) WITH (
      [storeHours] nvarchar(MAX) '$.store.operations.seasons[0].storeHours' AS JSON
   ) S
   CROSS APPLY OPENJSON(S.storeHours) A
);

但我希望它是动态的。有什么我想念的吗? CONCAT() 不工作的原因是什么?

编辑: 当我们想要存在的所有 storeHours 计数时,@Zhorov 解决方案的效果非常好。即所有季节中所有 storeHours 的总和。

我的要求是根据索引季节(例如:季节 [0])获取 storeHours 的计数。 如何实现?

【问题讨论】:

  • seasons 也是一个 JSON 数组,所以你有嵌套的 JSON 数组。你想要哪个计数?
  • 内层,storeHours
  • 你为什么使用这样的 JSON 而不是正确的表?车间工作时间是一个非常普通的静态模式。使用 JSON 只会增加延迟,不会增加灵活性
  • 我正在从 Mule 4 发送 JSON。在该平台上使用 JSON 非常灵活。

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


【解决方案1】:

答案:

如果我对您的理解正确,并且您想计算所有嵌套 $.storeHours 数组中的所有项目,则可以选择以下方法:

JSON:

DECLARE @count INT = 0;
DECLARE @destination nvarchar(max) = N'
{
  "store": {
    "storeId":123,
    "operations": {
      "seasons": [
        {
          "storeHours": []
        }
      ]
    }
  }
}'

声明:

SELECT @count = COUNT(*)
FROM OPENJSON(@destination, '$.store.operations.seasons') j1
CROSS APPLY OPENJSON(j1.[value], '$.storeHours') j2

SELECT @count

作为附加说明,始终指定nvarchar 变量的长度。当变量声明语句中未指定长度时,默认长度为 1。在您的情况下,@destination 变量的实际值只是$

更新:

如果您想...根据索引季节获取 storeHours 计数...,只需使用适当的 WHERE 子句:

DECLARE @count INT = 0;
DECLARE @destination nvarchar(max) = N'
{
  "store": {
    "storeId":123,
    "operations": {
      "seasons": [
        {
          "storeHours": [{},{},{}]
        },
        {
          "storeHours": [{},{}] 
        }
      ]
    }
  }
}'

SELECT @count = COUNT(*)
FROM OPENJSON(@destination, '$.store.operations.seasons') j1
CROSS APPLY OPENJSON(j1.[value], '$.storeHours') j2
WHERE CONVERT(int, j1.[key]) = 0

【讨论】:

  • 谢谢,有帮助。还有与nvarchar相关的信息
  • 嗨@Zhorov,你能帮我看看编辑的部分吗?
  • @SatyamPisal 检查更新的答案。谢谢,
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2010-10-17
  • 2010-12-30
  • 1970-01-01
  • 1970-01-01
  • 2013-09-03
  • 1970-01-01
相关资源
最近更新 更多