我正在为 SQL Server 2016 开发存储过程。
我必须这样做(下面的 sql 语句不起作用):
Insert into AggregationChildren (AggregationId, AggregationChildrenId, Position)
SELECT Parent, Serial, Position
FROM
OPENJSON (@json, '$.Aggregations')
WITH ( Parent nvarchar(20) '$.Parent',
Children nvarchar(max) AS JSON )
CROSS APPLY
OPENJSON (Children)
WITH ( Serial nvarchar(20), Position int)
我的问题是AggregationId
and是AggregationChildrenId
整数和Parent
and 。Serial
nvarchar(20)
和 之间存在关系Parent
,AggregationId
和 之间存在Serial
关系AggregationChildrenId
。我可以用Code
桌子得到它。
我知道当我必须为一列插入值时我该怎么做:
Insert into AggregationChildren (AggregationId)
Select CodeId from Code Where Serial = (SELECT Parent
FROM
OPENJSON (@json, '$.Aggregations')
WITH ( Parent nvarchar(20) '$.Parent',
Children nvarchar(max) AS JSON )
CROSS APPLY
OPENJSON (Children)
WITH ( Serial nvarchar(20), Position int))
我要插入的数据是:
{
...,
"Aggregations": [{
"Parent": "88962730000000004051",
"Children": [{
"Serial": "81861400000000020227",
"Position": "1"
}, {
"Serial": "81861400000000033191",
"Position": "2"
}, {
"Serial": "81861400000000046051",
"Position": "3"
},
...
]
}, {
"Parent": "88962730000000016653",
"Children": [{
"Serial": "81861400000001825849",
"Position": "1"
}, {
"Serial": "81861400000001832643",
"Position": "2"
}, {
"Serial": "81861400000001841911",
"Position": "3"
}, {
"Serial": "81861400000001850803",
"Position": "4"
}, {
"Serial": "81861400000001862474",
"Position": "5"
}, {
"Serial": "81861400000001874774",
"Position": "6"
}, {
"Serial": "81861400000001884159",
"Position": "7"
}, {
"Serial": "81861400000001898352",
"Position": "8"
}, {
"Serial": "81861400000001904764",
"Position": "9"
},
...
]
}]
}
但是,如果我必须使用两个,我该怎么办Select CodeId from Code Where Serial = (SELECT ...
?
我想我必须做这样的事情,但不做同样的选择三次:
Insert into AggregationChildren (AggregationId, AggregationChildrenId, Position)
Select CodeId from Code Where Serial = (SELECT Parent
FROM
OPENJSON (@json, '$.Aggregations')
WITH ( Parent nvarchar(20) '$.Parent',
Children nvarchar(max) AS JSON )
CROSS APPLY
OPENJSON (Children)
WITH ( Serial nvarchar(20), Position int)),
Select CodeId from Code Where Serial = (SELECT Serial
FROM
OPENJSON (@json, '$.Aggregations')
WITH ( Parent nvarchar(20) '$.Parent',
Children nvarchar(max) AS JSON )
CROSS APPLY
OPENJSON (Children)
WITH ( Serial nvarchar(20), Position int)),
SELECT Position
FROM
OPENJSON (@json, '$.Aggregations')
WITH ( Parent nvarchar(20) '$.Parent',
Children nvarchar(max) AS JSON )
CROSS APPLY
OPENJSON (Children)
WITH ( Serial nvarchar(20), Position int)
如果我理解正确:
dbfiddle在这里