从 JSON 数组中每行获取多条记录

Get multiple records per row from JSON array

我无法理解如何从单行中提取多个值,其中每行的 JSON 数组中都有源。

设置可能有点傻,但就是这样。

Table:

LogID       [int]
LogContent  nvarchar(max)

内容:

╔═══════╦══════════════════════════════════════════════════════════════════════════════════════════════════════════════════════╗
║ LogID ║ LogContent (JSON in nvarchar)                                                                                        ║
╠═══════╬══════════════════════════════════════════════════════════════════════════════════════════════════════════════════════╣
║ 1     ║ [{"DateTime":"2020-04-15T00:00:31","PropertyIWant":"ABC"}, {"DateTime":"2020-04-15T00:00:32","PropertyIWant":"DEF"}] ║
║ 2     ║ [{"DateTime":"2020-04-15T00:00:33","PropertyIWant":"GHI"}, {"DateTime":"2020-04-15T00:00:34","PropertyIWant":"JKL"}] ║
╚═══════╩══════════════════════════════════════════════════════════════════════════════════════════════════════════════════════╝

我想要的结果:

╔═══╦═════════════════════╦═══════════════╗
║   ║ DateTime            ║ PropertyIWant ║
╠═══╬═════════════════════╬═══════════════╣
║ 1 ║ 2020-04-15T00:00:31 ║ ABC           ║
║ 2 ║ 2020-04-15T00:00:32 ║ DEF           ║
║ 3 ║ 2020-04-15T00:00:33 ║ GHI           ║
║ 4 ║ 2020-04-15T00:00:34 ║ JKL           ║
╚═══╩═════════════════════╩═══════════════╝

我已经用 CROSS APPLY 和 JSON_QUERY 尝试了一些东西,但直到现在才成功。

它的一个例子是:

SELECT jt.PropertyIWant FROM Table CROSS APPLY
(
    SELECT * FROM OPENJSON (Table.LogContent) WITH (DateTime datetimeoffset](7), PropertyIWant nvarchar(255) '$.PropertyIWant')
) jt

但是当数据库中只有 77 行时,这将 return 219.851 行。在我的数据库中,它应该 return 大约 13.000 条记录。

如果您的数据库版本是 2016+,那么您可以使用 JSON_QUERY 嵌套在 OPENJSON 函数中,其中包含 WITH 解释返回列模型的子句:

SELECT DateTime, PropertyIWant
  FROM tab
  CROSS APPLY OPENJSON(JSON_QUERY(LogContent, '$'))
           WITH (DateTime      nvarchar(500) '$.DateTime',
                 PropertyIWant nvarchar(500) '$.PropertyIWant');

Demo