I have a procedure that should OPENJSON and insert into two tables at the same time, one row for every object within the JSON array. For example these two objects in the array will insert two rows of data into the "case_idents" table and output 2 case_ident_id's (101 & 102) and insert those two id's into the "case_to_case_idents" table. This procedure doesn't do that, instead only case_ident_id (102) gets inserted twice into the 'case_to_case_idents" table creating a duplicate instead of creating unique row objects.
CREATE PROCEDURE case_idents_addAll
@case_ident_id INT OUTPUT,
@seq_id INT OUTPUT,
@identObj NVARCHAR(MAX),
/*
DECLARE @case_ident_id INT
DECLARE @seq_id INT
DECLARE @identObj NVARCHAR(MAX) = N'[
{
"name": "Jack",
"entityTypeCd": "SM",
"identStatus": "PR",
"caseId": 10034,
"caseStatusCd": "NUA"
},
{
"name": "Jill",
"entityTypeCd": "SF",
"identStatus": "PR",
"caseId": 10035,
"caseStatusCd": "NA"
}
]';
EXECUTE case_idents_addAll @identObj=@identObj, @case_ident_id=@case_ident_id OUTPUT, @seq_id=@seq_id OUTPUT
*/
AS
BEGIN
INSERT INTO case_idents
(name, entity_type_cd, ident_status, case_id)
SELECT name, entity_type_cd, ident_status, case_id
FROM OPENJSON(@identObj)
WITH (
name NVARCHAR(50) '$.name',
entity_type_cd CHAR(5) '$.entityTypeCd',
ident_status CHAR(5) '$.identStatus',
case_id INT '$.caseId'
)
SET @case_ident_id=SCOPE_IDENTITY();
INSERT INTO case_to_case_ident
(case_id, case_ident_id, case_status_cd, case_ident_status_cd)
SELECT case_id, @case_ident_id, case_status_cd, case_ident_status_cd
FROM OPENJSON(@identObj)
WITH (
case_id INT '$.caseId',
case_status_cd CHAR(5) '$.caseStatusCd',
case_ident_status_cd CHAR(5) '$.identStatus'
)
SET @seq_id = SCOPE_IDENTITY();
END