英文:
How do I query a table in SQL Server that has a JSON column, where that JSON column can result in 0 or Many rows?
问题
我有一个表格 my_table
。以下是一个简化的视图:
id, the_json
1, {json json json}
2, {json}
3, {json json}
这里是 JSON 可能的样本:
{
"valid": false,
"messages": {
{
"message": "blah",
"error": true,
"detail": "something1"
}
{
"message": "blah blah",
"error": true,
"detail": "something2"
}
{
"message": "blah blah blah",
"error": false,
"detail": "something3"
}
}
}
我正在尝试编写一个查询以获得以下结果(为了可读性添加了行间隔):
id, message, error, detail
1, blah, true, something1
1, blah blah, true, something2
1, blah blah blah, false, something3
2, blah, true, something1
3, blah, true, something1
3, blah blah, true, something2
也就是说,JSON 中的每个消息节点都应该产生一行,并且应该与父表连接以显示 id。
英文:
I have a table my_table
. Here is a simplified view:
id, the_json
1, {json json json}
2, {json}
3, {json json}
Here is a sample of what the JSON can look like:
{
"valid":false,
"messages": {
{
"message": "blah",
"error": true,
"detail": "something1"
}
{
"message": "blah blah",
"error": true,
"detail": "something2"
}
{
"message": "blah blah blah",
"error": false,
"detail": "something3"
}
}
}
I am trying to write a query to get the following result (row gaps for visibility):
id, message, error, detail
1, blah, true, something1
1, blah blah, true, something2
1, blah blah blah, false, something3
2, blah, true, something1
3, blah, true, something1
3, blah blah, true, something2
Aka, each message node in the json should result in a row, and should join back to the parent table to show the id.
答案1
得分: 1
需要使用OPENJSON
函数来获取单独的行,并且需要使用模式来获取这些列。要针对表的每一行获取它,您需要使用APPLY
。
注意使用第二个参数直接跳到$.messages
。
SELECT
t.id,
j.*
FROM YourTable t
CROSS APPLY OPENJSON(t.the_json, '$.messages')
WITH (
message nvarchar(100),
error bit,
detail nvarchar(100)
) j;
英文:
You need to use the OPENJSON
function to get separate rows, and you need to do it with a schema to get these columns. To get it per row of your table, you need to APPLY
it.
Note the use of a second parameter to jumpt straight to $.messages
SELECT
t.id,
j.*
FROM YourTable t
CROSS APPLY OPENJSON(t.the_json, '$.messages')
WITH (
message nvarchar(100),
error bit,
detail nvarchar(100)
) j;
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论