[英]Expand row with an JSON Array inside a Column to multiple rows
I encountered a SQL-Data-Migration (SQL Server) problem and i hope, you can guide me in the right direction. 我遇到了SQL数据迁移(SQL Server)问题,希望您可以向正确的方向指导。
Assume, we have the table DataTable
(names simplified) with the following columns: 假设,我们有带有以下列的表
DataTable
(名称简化):
DataID | SomeForeignKey | SpecificDataValues | OtherSpecificDataValues
int | int | String | String
-------+----------------+--------------------+------------------------
0 | 1 | ['1','2'] | ['1', '2']
where SpecificDataValues
and OtherSpecificDataValues
are JSON arrays (like ['1', '2']
) 其中
SpecificDataValues
和OtherSpecificDataValues
是JSON数组(例如['1', '2']
)
Now i want to migrate this table (with an SQL Migration script at best) to a new table: 现在,我想将此表(最好使用SQL迁移脚本)迁移到新表:
DataValuesTable
DataID | SomeForeignKey | SpecificDataValues | OtherSpecificDataValues
-------+----------------+--------------------+------------------------
0 | 1 | 1 | 1
1 | 1 | 2 | 2
So, i basically want to generate a new row in a new table for each value, stored in "SpecificDataValues" and "OtherSpecificDataValues" 所以,我基本上想在新表中为每个值生成一个新行,存储在“ SpecificDataValues”和“ OtherSpecificDataValues”中
I already checked, that there are SQL functions to work with JSON (OPENJSON, JSON_QUERY) but i was not able to produce the desired result using this tools. 我已经检查过,有可以使用JSON的SQL函数(OPENJSON,JSON_QUERY),但是我无法使用此工具产生所需的结果。
I hope, you can show me the right direction. 希望您能告诉我正确的方向。
One solution is to use OPENJSON
twice. 一种解决方案是两次使用
OPENJSON
。 It will generate Array(2) x Array(2) = 4 rows, the ones you're interested in are the ones where the index positions match: 它将生成Array(2)x Array(2)= 4行,您感兴趣的是索引位置匹配的行:
SELECT DataID, SomeForeignKey, j1.value, j2.value
FROM t
CROSS APPLY OPENJSON(SpecificDataValues) AS j1
CROSS APPLY OPENJSON(OtherSpecificDataValues) AS j2
WHERE j1.[key] = j2.[key]
Another solution is to use OPENJSON
and JSON_VALUE
together: 另一个解决方案是一起使用
OPENJSON
和JSON_VALUE
:
SELECT DataID, SomeForeignKey, j1.value, JSON_VALUE(OtherSpecificDataValues, CONCAT('$[', CAST(j1.[key] AS INT), ']'))
FROM t
CROSS APPLY OPENJSON(SpecificDataValues) AS j1
Note that your "JSON" is invalid. 请注意,您的“ JSON”无效。 Strings must be enclosed inside
"
. 字符串必须包含在
"
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.