Reputation: 5107
I feel like this should be fairly straightforward, but I'm having an issue figuring out the best way to do this
I have a number of subitems in this subitem_to_item_status table that have a status but I need to insert a record for all subItems that aren't there yet. I don't need to update what's in there, I'm really just trying to replicate an 'insert/ignore'
Sample Data for subitems
ITEM_SUBITEMT
item_subitem_id | creator_identifier
-----------------------------------------
12 12345
13 12345
14 12345
15 12345
16 12345
17 12345
18 12345
19 12345
20 12345
21 12345
22 12345
SUBITEM_TO_ITEM_STATUS
SUBITEM_ID | ITEM_STATUS_ID | CREATED_BY_IDENTIFIER
------------------------------------------------------------
12 1 12345
15 1 12345
16 1 12345
20 1 12345
So with that data, I just need to insert records from the first table that don't have the id 12,15,16 or 20
MERGE INTO schema.SUBITEM_TO_ITEM_STATUS (SUBITEM_ID,ITEM_STATUS_ID, CREATED_BY_IDENTIFIER,ROWCHANGE,CREATED_AT) AS T
USING( (SELECT ITEM_SUBITEM_ID, 1, CREATOR_IDENTIFIER, NOW(),NOW() FROM schema.ITEM_SUBITEMT) AS S
ON S.ITEM_SUBITEM_ID = T.SUBITEM_ID
WHEN NOT MATCHED THEN INSERT;
Upvotes: 0
Views: 1241
Reputation: 12314
Wrong MERGE
statement.
Try this:
MERGE INTO schema.SUBITEM_TO_ITEM_STATUS T
USING (SELECT ITEM_SUBITEM_ID, 1 AS ITEM_STATUS_ID, creator_identifier FROM schema.ITEM_SUBITEMT) S ON S.ITEM_SUBITEM_ID = T.SUBITEM_ID
WHEN NOT MATCHED THEN
INSERT (SUBITEM_ID, ITEM_STATUS_ID, CREATED_BY_IDENTIFIER)
VALUES (S.item_subitem_id, S.ITEM_STATUS_ID, S.creator_identifier);
Upvotes: 1
Reputation: 1269633
Why not use insert
?
insert into SUBITEM_TO_ITEM_STATUS (SUBITEM_ID, ITEM_STATUS_ID, CREATED_BY_IDENTIFIER)
select item_subitem_id, 1, creator_identifier
from ITEM_SUBITEMT
where item_subitem_id not in (12, 15, 16, 20);
If what you mean is that you don't want duplicates in the table, you can try:
insert into SUBITEM_TO_ITEM_STATUS (SUBITEM_ID, ITEM_STATUS_ID, CREATED_BY_IDENTIFIER)
select item_subitem_id, 1, creator_identifier
from ITEM_SUBITEMT s
where not exists (select 1
from SUBITEM_TO_ITEM_STATUS tis
where tis.item_subitem_id = s.item_subitem_id
);
Upvotes: 0