SQL查询以检查JSON列中键是否存在且其值为空。

huangapple go评论52阅读模式
英文:

SQL query to check if a key exists and its value is null in JSON column

问题

I am trying to select rows that have a JSON column where there is an object with a given key and the value is null.

Example:

{
  "test": null
}

I tried the below query:

SELECT * FROM Table WHERE JSON_VALUE(Column, '$.test') IS NULL

Result columns:

  • {"test":null}
  • {}
  • {"prod":1}

This returns the expected rows but also returns rows that don't have such a key.

How to return only the rows that have the key exist.

英文:

I am trying to select rows that has a JSON column where there is an object with a given key and value is null.

Example:

{
  "test": null
}

I tried the below query:

SELECT * FROM Table WHERE JSON_VALUE(Column, '$.test') IS NULL

Result columns:

  • {"test":null}
  • {}
  • {"prod":1}

This returns the expected rows but also returns rows that doesn't have such key.

How to return only the rows that have the key exist.

答案1

得分: 1

SQL Server 2016+:

您可以尝试使用OPENJSON()和默认模式解析JSON。结果 是一个包含列key(一个nvarchar(4000)值,包含指定属性的名称)、value(一个nvarchar(max)值,包含属性的值)和type的表,因此您可以实现适当的WHERE子句。

SELECT * 
FROM [Table] t
WHERE EXISTS (  
   SELECT 1
   FROM OPENJSON(t.[Column])
   WHERE [key] = N'test' AND [value] IS NULL
)

SQL Server 2022+:

另一个选择是结合使用JSON_PATH_EXISTS()JSON_VALUE()

SELECT * 
FROM [Table]
WHERE 
  JSON_PATH_EXISTS([Column], '$.test') = 1 AND
  JSON_VALUE([Column], '$.test') IS NULL

注意:

当您使用JSON_VALUE()strict路径修饰符时,对于错误的路径表达式,结果将是错误的:

SELECT * 
FROM [Table] 
WHERE JSON_VALUE([Column], 'strict $.test') IS NULL
英文:

SQL Server 2016+:

You may try to parse the JSON with OPENJSON() and default schema. The result is a table with columns key (an nvarchar(4000) value that contains the name of the specified property), value (an nvarchar(max) value that contains the value of the property) and type, so you can implement an appropriate WHERE clause.

SELECT * 
FROM [Table] t
WHERE EXISTS (  
   SELECT 1
   FROM OPENJSON(t.[Column])
   WHERE [key] = N'test' AND [value] IS NULL
)  

SQL Server 2022+:

Another option is a combination of JSON_PATH_EXISTS() and JSON_VALUE():

SELECT * 
FROM [Table]
WHERE 
  JSON_PATH_EXISTS([Column], '$.test') = 1 AND
  JSON_VALUE([Column], '$.test') IS NULL

Note:

When you use JSON_VALUE() and a strict path modifier, the result is an error for a wrong path expression:

SELECT * 
FROM [Table] 
WHERE JSON_VALUE([Column], 'strict $.test') IS NULL

答案2

得分: -2

You have to use JSON_EXTRACT

For example:

Select *
from table
where JSON_EXTRACT(Column, '$.test') IS NOT NULL

英文:

You have to use JSON_EXTRACT

For example:

Select *
from table
where JSON_EXTRACT(Column, '$.test') IS NOT NULL

huangapple
  • 本文由 发表于 2023年4月11日 11:59:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/75982291.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定