【问题标题】:T-SQL JSON: JSON_QUERY is returning a json string after comparing the object with a stringT-SQL JSON:JSON_QUERY 在将对象与字符串进行比较后返回 json 字符串
【发布时间】:2020-11-06 14:12:35
【问题描述】:

仅当 JSON 包含特定字段/属性时,我才尝试返回 JSON_QUERY 字段,但是当我将其与字符串(即字段名称)进行比较时,该函数不会返回 JSON...

单个代码没有比较:

SELECT Field1, Field2
       ,JSON_QUERY('[' + json.CrossApplyQuery + ']', '$') AS [Returns_JSON]

返回:

Field1   |  Field2  |  Returns_JSON
Value1   |  Value2  |  [{"SomeQueryField":"SomeStringValue"]}]

使用 JSON 进行比较的代码:

SELECT Field1, Field2
       ,CASE WHEN CHARINDEX('_JsonProperty', UPPER(json.CrossApplyQuery)) > 0 THEN JSON_QUERY('[' + json.CrossApplyQuery + ']', '$') ELSE NULL END AS [Returns_String]
       ,CASE WHEN Exists(Select * FROM OPENJSON(JSON_QUERY('[' + json.CrossApplyQuery + ']', '$'),'$') WHERE value like '%_JsonProperty%') THEN JSON_QUERY('[' + json.CrossApplyQuery + ']', '$') ELSE NULL END AS [Returns_String_Too]

返回:

Field1   |  Field2  |  Returns_String                               |  Returns_String_Too
Value1   |  Value2  |  "[{\"SomeQueryField\":\"SomeStringValue\"}]  |  "[{\"SomeQueryField\":\"SomeStringValue\"}]

如果我不使用 JSON 字段进行比较(任何其他条件),它可以工作!

SELECT Field1, Field2
       ,CASE WHEN 0 < 1 THEN JSON_QUERY('[' + json.CrossApplyQuery + ']', '$') ELSE NULL END AS [Returns_JSON]

返回:

Field1   |  Field2  |  Returns_JSON
Value1   |  Value2  |  [{"SomeQueryField":"SomeStringValue"]}]

问题:如何检查 JSON 是否包含字段/属性而不将其更改为字符串?

【问题讨论】:

  • JSON 是一个字符串;通常是nvarchar(MAX)。你的意思是你如何阅读它而不把它变成一个?您实际上是将其存储在varbinary 中吗?
  • 我知道 Json 本质上是一个字符串... ,只是返回...当我将 json 对象与某个字符串进行比较时,返回发生了变化...

标签: sql tsql sql-server-2017 json-query open-json


【解决方案1】:

使用这种方式解决的问题:

JSON_QUERY('[' + CASE WHEN CHARINDEX('_JsonProperty', UPPER(json.CrossApplyQuery)) > 0 THEN json.CrossApplyQuery ELSE NULL END + ']', '$') [Returns_JSON]

不知道为什么,但它起作用了...... 谢了!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-04
    • 2023-03-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-23
    相关资源
    最近更新 更多