I have a table with an auto incrementing id
and a unique constraint across two columns, keycol1
and keycol2
.
Suppose the table has this data:
H| (id, keycol1, keycol2, col1, col2)
| (1, 'A', 'B', 'A', 'E' )
| (2, 'A', 'C', 'J', 'K' )
| (3, 'A', 'D', 'H', 'I' )
I then use a MERGE
statement to update all the records corresponding to keycol1
:
MERGE tablename trg
USING (VALUES ('A','B','C','D'),
('A','C','E','F'),
('A','E','K','F'),
('A','F','L','M')) src(keycol1, keycol2, col1, col2)
ON trg.keycol = src.keycol AND trg.keycol2 = src.keycol2
WHEN MATCHED THEN
UPDATE
SET col1 = src.col1, col2 = src.col2
WHEN NOT MATCHED THEN
INSERT (keycol1, keycol2, col1, col2)
VALUES (src.keycol1, src.keycol2, src.col1, src.col2);
This works great to update existing records or add additional records as needed. In our example, rows 1 and 2 will be updated, and rows 4 and 5 will be inserted.
How can I modify the query to delete any rows in tablename
where keycol1 = 'A' that were not affected by the MERGE statement? In our example, row 3 should be deleted.
Prior to trying merge, I attempted to solve this by using a DELETE followed by INSERTing multiple values in one transaction. This had the effect of auto incrementing the ID column each time. Since the merge operation would be frequent and there is a lot more than 3 rows involved in each transaction, I'm trying to find something more efficient and avoid the risk of overflowing the id column.