Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Behavior of Sequence in Oracle Merge Statements

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,

like image 280
Incognito Avatar asked Oct 20 '11 07:10

Incognito


People also ask

How does merge work in Oracle?

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.

What does sequence do in Oracle?

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.

What is merge statement in Oracle with example?

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.

What is Oracle sequence Nextval?

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.


Video Answer


2 Answers

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

like image 64
Incognito Avatar answered Sep 17 '22 23:09

Incognito


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

like image 42
Mohammed Ismail Avatar answered Sep 17 '22 23:09

Mohammed Ismail