Recently, I came across an issue related to incrementing sequence values inside a merge statement.
The MERGE INSERT clause, is accessing a sequence to populate one of the columns. I noted that, it does not matter how many rows are actually eligible for insertion, the sequence ends up incrementing for the total number of records in the source SELECT clause.
Why that may be happening?
I am working on Oracle 10gR2
Thanks,
Use the MERGE statement to select rows from one or more sources for update or insertion into a table or view. You can specify conditions to determine whether to update or insert into the target table or view. This statement is a convenient way to combine multiple operations.
In Oracle, you can create an autonumber field by using sequences. A sequence is an object in Oracle that is used to generate a number sequence. This can be useful when you need to create a unique number to act as a primary key.
Merge is one statement that allows you to do either an insert or an update as needed. To use it, you need to state how values in the target table relate to those in the source in the join clause. Then add rows in the when not matched clause. And update them using when matched.
The Oracle NEXTVAL function is used to retrieve the next value in a sequence. The Oracle NEXTVAL function must be called before calling the CURRVAL function, or an error will be thrown. No current value exists for the sequence until the Oracle NEXVAL function has been called at least once.
I have found the answer. As per Oracle documentation, the sequence will be incremented for each merged record and it does not matter how many records are actually inserted.
http://download.oracle.com/docs/cd/B19306_01/server.102/b14200/pseudocolumns002.htm#sthref809
You can solve this by using a function to increment the value like this
CREATE OR REPLACE
FUNCTION seq_nextval_on_demand (p_seq_name IN VARCHAR2)
RETURN NUMBER
IS
v_seq_val NUMBER;
BEGIN
EXECUTE IMMEDIATE 'select ' || p_seq_name || '.nextval from dual'
INTO v_seq_val;
RETURN v_seq_val;
END seq_nextval_on_demand;
the logic is function is called only when "insert" branch of merge statement is really used.
for further refer this http://alex-td.blogspot.in/2012/07/sequences-nextval-in-merge-operator.html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With