I have a table that has an ID field with a trigger (so it's essentially an IDENTITY field) as my primary key. I mostly don't care about that.
The rest of the data are several linking keys, and I want to query my data, and if any of those keys have changed, add a new record with a new effective date. If all the keys are the same, then nothing should be added.
However, even when all of the keys match, it is adding new records. All of the fields I care about are exactly the same, so I'm essentially getting duplicate records, but with a new ID and new effective date.
I'll simplify my code a bit, but this is essentially what I have:
MERGE_TABLE (
merge_ID NUMBER(18) PRIMARY KEY NOT NULL,
asof_Date Date,
keyA varchar2(10 byte),
keyB varchar2(10 byte),
keyC varchar2(10 byte),
table_date Date)
There is a trigger on merge_ID on insert to use a sequence.
MERGE INTO merge_table mt
USING (
select keyA, keyB, keyC, table_date
from table -- it's actually a complex query, but it's getting data
) tbl
ON (rtrim(tbl.keyA) = rtrim(mt.keyA)
AND rtrim(tbl.keyB) = rtrim(mt.keyB)
AND rtrim(tbl.keyC) = rtrim(mt.keyC))
WHEN NOT MATCHED THEN
INSERT (asof_Date, keyA, keyB, keyC, table_date)
VALUES (sysdate, tbl.keyA, tbl.keyB, tbl.keyC, tbl.table_date)
If my MERGE_TABLE starts with the following data:
merge_ID asof_Date keyA keyB keyC table_date
10 1/1/2018 333 456 987 12/31/2017
11 1/1/2018 444 234 876 12/31/2017
12 1/1/2018 222 789 654 12/31/2017
then, after running it, I have the following data:
merge_ID asof_Date keyA keyB keyC table_date
10 1/1/2018 333 456 987 12/31/2017
11 1/1/2018 444 234 876 12/31/2017
12 1/1/2018 222 789 654 12/31/2017
13 3/22/2018 333 456 987 12/31/2017
14 3/22/2018 444 234 876 12/31/2017
15 3/22/2018 222 789 654 12/31/2017
My keys all matched, but it did an insert anyway. Why?
If KeyB had changed on the first record from 456 to 678, the data I would want is:
merge_ID asof_Date keyA keyB keyC table_date
10 1/1/2018 333 456 987 12/31/2017
11 1/1/2018 444 234 876 12/31/2017
12 1/1/2018 222 789 654 12/31/2017
13 3/22/2018 333 678 987 12/31/2017