Sql server OPENJSON在解析JSON属性时忽略大小写
假设有一个表a包含列Sql server OPENJSON在解析JSON属性时忽略大小写,sql-server,open-json,Sql Server,Open Json,假设有一个表a包含列信息,数据以JSON格式存储在那里。存储在那里的JSON字符串可能具有属性Comment和Timestamp或属性Comment和Timestamp。像这样: [{"Timestamp":"2018-04-11 18:14:59.9708","Comment":"first comment"}] [{"timestamp":"2017-04-11 18:14:59.9
信息
,数据以JSON格式存储在那里。存储在那里的JSON字符串可能具有属性Comment
和Timestamp
或属性Comment
和Timestamp
。像这样:
[{"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;
是否有语法通过忽略大小写同时返回Comment
或Comment
属性。如中所述,带有显式模式(带子句),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
如中所述,使用显式模式(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
我一直在寻找其他方法,但还没有成功。我决定单独捕获所有这些JSON属性,然后使用union。我正在寻找其他方法,但还没有成功。我决定单独捕获所有这些JSON属性,然后使用union。