SQL Server JSON_QUERY 根据数值选择 JSON 对象。

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

SQL Server JSON_QUERY Select Json object based on value

问题

以下是翻译好的内容:

我在SQL Server表中有以下JSON数据:

{
"Mapping": [
{
"SourceFieldId": 46,
"TargetField": {
"output_field_description": "Last Name",
"output_header_field": "Last Name",
"required": "Y",
"data_type": "TEXT",
"date_format": "",
"number_of_decimals": "",
"max_length": 30,
"field": 1
}
},
{
"SourceFieldId": 46,
"TargetField": {
"output_field_description": "Last Name",
"output_header_field": "Last Name",
"required": "Y",
"data_type": "TEXT",
"date_format": "",
"number_of_decimals": "",
"max_length": 30,
"field": 1
}
}
]
}

我尝试根据SourceFieldID获取对象。

我尝试了几种变体,但都没有成功:

  1. SELECT
  2. JSON_query(MapJSON, '$.Mapping')
  3. FROM
  4. MapHistories
  5. WHERE
  6. JSON_VALUE(MapJSON, '$.Mapping.SourceFieldID') = 1

这是可能的吗?

英文:

I have the following JSON data in a SQL Server table:

  1. {
  2. "Mapping": [
  3. {
  4. "SourceFieldId": 46,
  5. "TargetField": {
  6. "output_field_description": "Last Name",
  7. "output_header_field": "Last Name",
  8. "required": "Y",
  9. "data_type": "TEXT",
  10. "date_format": "",
  11. "number_of_decimals": "",
  12. "max_length": 30,
  13. "field": 1
  14. }
  15. },
  16. {
  17. "SourceFieldId": 46,
  18. "TargetField": {
  19. "output_field_description": "Last Name",
  20. "output_header_field": "Last Name",
  21. "required": "Y",
  22. "data_type": "TEXT",
  23. "date_format": "",
  24. "number_of_decimals": "",
  25. "max_length": 30,
  26. "field": 1
  27. }
  28. }
  29. ]
  30. }

I am trying to grab the object based on the SourceFieldID.

I've tried a few variations of this, with no luck:

  1. SELECT
  2. JSON_query(MapJSON, '$.Mapping')
  3. FROM
  4. MapHistories
  5. WHERE
  6. JSON_VALUE(MapJSON, '$.Mapping.SourceFieldID') = 1

Is this possible?

答案1

得分: 1

使用OPENJSON来解析JSON作为第一个参数,并返回包含来自JSON对象的数据的一个或多个行:

  1. SELECT SalesOrderJsonData.*
  2. FROM MapHistories AS Tab
  3. CROSS APPLY OPENJSON(Tab.MapJSON, N'$.Mapping') WITH (
  4. SourceFieldId int N'$.SourceFieldId',
  5. TargetField nvarchar(max) N'$.TargetField' AS JSON
  6. ) AS SalesOrderJsonData
  7. where SalesOrderJsonData.SourceFieldId = 46

此处演示

英文:

You can do it using OPENJSON to parses the json as the first argument and returns one or more rows containing data from the JSON objects :

  1. SELECT SalesOrderJsonData.*
  2. FROM MapHistories AS Tab
  3. CROSS APPLY OPENJSON(Tab.MapJSON, N'$.Mapping') WITH (
  4. SourceFieldId int N'$.SourceFieldId',
  5. TargetField nvarchar(max) N'$.TargetField' AS JSON
  6. ) AS SalesOrderJsonData
  7. where SalesOrderJsonData.SourceFieldId = 46

Demo here

huangapple
  • 本文由 发表于 2023年4月10日 22:00:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/75977774.html
匿名

发表评论

匿名网友

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

确定