0

假设有一个表 A 有 column Information,数据以 JSON 格式存储在那里。存储在那里的 JSON 字符串可能具有属性CommentTimestamp或属性commenttimestamp. 像这样:

[{"Timestamp":"2018-04-11 18:14:59.9708","Comment":"first comment"}]
[{"timestamp":"2017-04-11 18:14:59.9708","comment":"second comment"}]
[{"Timestamp":"2019-04-11 18:14:59.9708","Comment":"third comment"}, {"timestamp":"2017-04-11 18:14:59.9708","comment":"last comment"}]

下面的脚本仅解析大写属性的 JSON 字符串,并为小写的 JSON 字符串抛出错误。

Select jsonInfo.*
From OPENJSON(@Information, N'$')
    with(
        Comment nvarchar(max) N'$.Comment',
        TimeStamp datetime '$.Timestamp'
    ) as jsonInfo;

是否有任何语法通过忽略大小写返回两者Commentcomment属性。

4

1 回答 1

2

文档中所述,使用显式模式(WITH子句),OPENJSON()将输入 JSON 表达式中的键与子句中的列名WITH匹配,并且匹配区分大小写。但是,作为一种可能的解决方法,您可以尝试使用OPENJSON()默认模式和条件聚合:

陈述:

DECLARE @information nvarchar(max) = N'[
   {"Timestamp":"2019-04-11 18:14:59.9708","Comment":"third comment"}, 
   {"timestamp":"2017-04-11 18:14:59.9708","comment":"last comment"}
]'

SELECT 
   MAX(CASE WHEN LOWER(j2.[key]) = N'timestamp' THEN j2.[value] END) AS [TimeStamp],
   MAX(CASE WHEN LOWER(j2.[key]) = N'comment' THEN j2.[value] END) AS [Comment]
FROM OPENJSON(@information, '$') j1
CROSS APPLY OPENJSON(j1.[value]) j2
GROUP BY j1.[key]

结果:

TimeStamp                   Comment
-----------------------------------------
2019-04-11 18:14:59.9708    third comment
2017-04-11 18:14:59.9708    last comment
于 2020-08-04T06:08:31.730 回答