Doubt Regarding Merge Statement in Oracle

Hi,
I have an SP which takes 3 parameters Lets say
(in_empid, in_empname,in_age)
here in_empid corresponds to the empid ie primary key for update/insert
Now which of the approach will be better. Will there be problem in using Merge statements for updates/insert
1. Approach 1
Add one more flag in parameters in_action . Now if in_action = 'U' then write an update statement.If in_action='I' then write insert stmnt
2. Approach 2
write a merge stmnt as follows
merge into employee e using
( select in_empid, in_empname,in_age from dual ) b
on  ( b.in_empid = e.empid)
WHEN MATCHED THEN
  UPDATE SET e.ENAME = in_empname,
                       e.age = in_age
WHEN NOT MATCHED THEN
  INSERT
  VALUES (in_empid,in_empname,in_age) something like that
Which would be preferred? I mean is there any restriction that merge can be used only to merge 2 tables?what are the drawbacks of using Merge?
Regds,
S

Hi cd,
Thanks for the reply.
Actaully I was keeping the front-end code also in mind.
If we click an update button, then they will have to manage a flag till the end to say that transaction was update. whereas when its an insert of new record, they have to maintain a falg till end to imply that the transaction was insert.
I want to avoid this so that they need not maintain additional flag.
Hence I was thinking of using MERGE statement.
Will there be any problem in using merge for such scenarios?
Regds,
S

Similar Messages

  • Instead of trigger is NOT firing for merge statements in Oracle 10gR2

    The trigger fires fine for a update statement, but not when I use a merge statement
    with an update clause. Instead I get the normal error for the view ( which is a union all view, and therefore not updatable.)
    The error is :-
    ORA-01733: virtual column not allowed here
    oracle release is 10.2.0.2 for AIX 64L
    Is this a known bug ?
    I've used a multi-table insert statement to work around the problem for inserts, but
    for updates, I'd really like to be able to use a merge statement instead of an update.
    Mark.

    This is my cut-down version :-
    In this case case I'm getting an :-
    ORA-01446: cannot select ROWID from, or sample, a view with DISTINCT, GROUP BY, etc.
    rather then the ora-01733 error I get in the real code ( which is an update from an involved
    XML expression - cast to a table form)
    create table a ( a int primary key , b char(30) ) ;
    create table b ( a int primary key , b char(30) ) ;
    create view vw_a as
    select *
    from a
    union all
    select *
    from b ;
    ALTER VIEW vw_a ADD (
    PRIMARY KEY
    (a) DISABLE);
    DROP TRIGGER TRG_IO_U_ALL_AB;
    CREATE OR REPLACE trigger TRG_IO_U_ALL_AB
    instead of update ON vw_a
    for each row
    begin
    update a targ
    set b = :new.b
    where targ.a = :new.a
    if SQL%ROWCOUNT = 0
    then
         update b targ
         set b      = :new.b
         where targ.a = :new.a
    end if ;
    end ;
    insert into a values (1,'one');
    insert into a values (2,'two');
    insert into a values (3,'three');
    insert into b values (4,'quatre');
    insert into b values (5,'cinq');
    insert into b values (6,'six');
    commit;
    create table c as select a + 3 as a, b from a ;
    commit;
    merge into vw_a targ
    using (select * from c ) src
    on ( targ.a = src.a )
    when matched
    then update
    set targ.b = src. b
    select * from vw_a ;
    rollback ;
    update vw_a b
    set b = ( select c.b from c where b.a = c.a )
    where exists ( select c.b from c where b.a = c.a ) ;
    select * from vw_a ;
    rollback ;

  • The new MERGE statement in Oracle 9i

    Has anyone used the new Merge statement to process large amounts of data? Currently we use PL/SQL to update/insert into our tables when we are loading large amounts of data (close to one million rows) because we can set commit points and avoid rollback problems. I am wondering if we use Merge instead how this will affect rollback? Are we still going to have to code for this problem?
    Thanks in advance!

    Thanks for the suggestions. Our problem is that the base table contains 50 million rows and seven indexes, and each month we try to insert/update one million rows. Some of the data in the base table is historical so if we implemented your solution we would lose any records not being updated.
    What I am really trying to determine is if the MERGE statement has any redo log ramifications. Will we run in rollback space problems if we implement it instead of running PL/SQL in the following format:
    FOR cur_rec in c1 LOOP
    UPDATE table a
    SET col a = cur_rec.col a, ...
    WHERE ...
    IF SQL%NOTFOUND THEN
    INSERT (col a , col b, col c...)
    VALUES (cur_rec.col a, cur_rec.col b...);
    END IF;
    We commit every 10,000 records (as determined by SQL%ROWCOUNT). This can be time comsuming and Oracle claims that the new MERGE command will avoid costly overhead and reduce data scans. However, I am concerned that we may hit rollback problems if we implement a straight SQL statement such as MERGE. Any thoughts?

  • Error in Merge statement for Oracle 10gR2

    Hi,
    When I use the MERGE statement to copy data across a database link (from 10gR2 to 10gR2 database), if I have both an update and insert clause it works fine, but if I omit the insert clause and have just update on its own, I get error "ORA-02064: distributed operation not supported".
    Can anyone help on this

    This came up in a thread last week, the 10g versions of MERGE (without INSERT or with DELETE) did not appear to work over DB links.

  • Just a FYI regarding Case statements in ORacle 8i in pl/sql

    Well..I saw numerous posts in this forum regarding not being able to do case statement within pl/sql. Well..you can do
    that using dynamic SQL. IT works like a champ.

    Hi,
    Try first to (re)compile ll invalid objects. then
    you can run:
    select owner,type,count(*) from all_errors
    group by owner,typeif you still have uncompiled objects, then report the different errors:
    select * from all_errors...

  • Merge Statement in Oracle

    I have two tables.Table 1 and Target.
    I am using Table 1 as source to update records in target table.
    I am joining the two tables on common column named ID. Datatype for ID in table 1 is VARCHAR whereas it is NUMBER in target table.
    Also, Updatedate column have datatype VARCHAR in table 1 whereas it is TIMESTAMP in target table.
    I am using the following code but getting errors:
    1. Error in executing ODCIEXTTABLEFETCH
    2.NON-NUMERIC character is found where a numeric was expected
    Code i am using:
    MERGE
    INTO target tgt
    USING (select
    to_numbet(ID),
    ADDRESS,
    CITY,
    STATE,
    COUNTRY,
    ZIP
    from TABLE1 a,target b where a.ID = b.ID and
    to_date(a.updatedate,'mm/dd/yyyy') > (select max(updatedate) from target)and rownum < 100) src
    ON (src.ID = tgt.ID)
    WHEN MATCHED
    THEN
    UPDATE
    SET tgt.address = src.address,
    tgt.city = src.city,
    tgt.state = src.state,
    tgt.zip = src.zip,
    tgt.country = src.country
    WHEN NOT MATCHED
    THEN
    INSERT (ID,address,city,zip,state,country)
    VALUES (src.ID,src.address,src.city,src.zip,src.state,src.country)
    Please suggest some solution to rectify this issue.
    Thanks

    user11018028 wrote:
    I have two tables.Table 1 and Target.
    I am using Table 1 as source to update records in target table.
    I am joining the two tables on common column named ID. Datatype for ID in table 1 is VARCHAR whereas it is NUMBER in target table.
    Also, Updatedate column have datatype VARCHAR in table 1 whereas it is TIMESTAMP in target table.
    I am using the following code but getting errors:
    1. Error in executing ODCIEXTTABLEFETCH
    2.NON-NUMERIC character is found where a numeric was expected
    Code i am using:
    MERGE
    INTO target tgt
    USING (select
    to_numbet(ID),
    ADDRESS,
    CITY,
    STATE,
    COUNTRY,
    ZIP
    from TABLE1 a,target b where a.ID = b.ID and
    to_date(a.updatedate,'mm/dd/yyyy') > (select max(updatedate) from target)and rownum < 100) src
    ON (src.ID = tgt.ID)
    WHEN MATCHED
    THEN
    UPDATE
    SET tgt.address = src.address,
    tgt.city = src.city,
    tgt.state = src.state,
    tgt.zip = src.zip,
    tgt.country = src.country
    WHEN NOT MATCHED
    THEN
    INSERT (ID,address,city,zip,state,country)
    VALUES (src.ID,src.address,src.city,src.zip,src.state,src.country)
    Please suggest some solution to rectify this issue.
    ThanksID column contains non-numeric data

  • Doubt regarding Message statement

    Hi,
    I want to pop up a message in which I want the valye of X tp be replaced by its value.
    DATA: X(3) TYPE C VALUE 'FFF'.
    MESSAGE ID 'ERROR MESSAGE' TYPE 'E' NUMBER '000' WITH 'COMPUTED' '&X&'.
    But this does not work.
    Can someone help me out ?
    Tushar

    Tushar,
    The ID part refers to a Message Class. Here you specified 'Error Message' which is an invalid name as well as being not in customer name space (does not start with Y or Z). You can examine existing Message Classes as well as create and maintain with Txn SE91.
    A message with Number mentioned with the number part should exist in the specified Message Class. In your case the message should have at least  two '&' symbols as place holders for two variable you are going to substitute from your ABAP.
    Do not enclose a variable name with  & and  quotes in the ABAP code.
    As already mentioned in one of the replies, Error Messages by default are not dispalyed in a popup. It is a user setting.
    Also, please read the F1 help for the Message statement.
    Cheers,
    Ramki Maley.

  • Oracle 9.2i - Log Errors in a Merge Statement

    Hi all,
    I want to log errors in a merge statement in way to allow the statement to finish without rollback. I see that in Oracle 10g2 it is possible with "LOG ERRORS INTO err$_dest ('MERGE') REJECT LIMIT UNLIMITED;" instruction but, apparently, it's not possible in Oracle 9.2i.
    Is there another way to solve this problem?

    Depending on what type of errors you expect, you may be helped by deferring your constraints: unique, foreign key and check constraints can be deferred; that means they are only enforced when you commit.
    You could defer all constraints, perform the bulk insert and then instead of committing you first try to set all constraints to immediate. If this fails, there are errors. If it does not, you can commit.
    To find the exact errors, you can try to switch all deferred constraints back to immediate one by one. The ones that succeed are not violated by your transaction, oinly the ones that fail to switch to immediate are not met by your transaction.
    For the violated constraints, you can find the offending records by simply selecting them. For example if the check constraint states Col X + Col Y < 10000 you will find the offending records by selecting all records where not (Col X + Col Y < 10000 ). Unfortunately we have no better mechanism than this for finding the records that are in violation of the rules.
    best regards
    Lucas

  • Merge Statement !!!! difference in Oracle 9i and Oracle XE

    Hi All ,
    I am using a Merge statement for multiplying a column......which works fine in XE but not in Oracle 9i
    CODE
    *======*
    MERGE INTO MULTIPLY T USING
    (SELECT CONV,ITEM FROM MULTIPLY WHERE TYP='P') X ON
    (T.ITEM= X.ITEM)
    WHEN MATCHED THEN UPDATE SET T.CONV =X.CONV * T.CONV WHERE TYP!='P'
    What shud I need to do in order to get the same result in Oracle 9i.....
    I understand that I used use one more line WHEN NOT MATCHED ..... but I am getting an Error in the Update statement where clause , whether it is not possible to combine where clause in the Merge statement
    Sample data:
    ITM     CONV     TYP
    ===============
    A     2     
    A     5     
    A     4     P
    A     2     
    Output; which I am getting in Oracle XE but not in Oracle 9i
    ======================================
    ITM CONV TYP
    === ==== =====
    A 2 *4
    A 5 *4
    A 4 P
    A 2*4
    BANNER
    ==========
    Oracle Database 10g Express Edition Release 10.2.0.1.0 - Product
    PL/SQL Release 10.2.0.1.0 - Production
    CORE     10.2.0.1.0     Production
    TNS for 32-bit Windows: Version 10.2.0.1.0 - Production
    NLSRTL Version 10.2.0.1.0 - Production
    BANNER_
    Oracle9i Enterprise Edition Release 9.2.0.5.0 - Production
    PL/SQL Release 9.2.0.5.0 - Production
    CORE     9.2.0.6.0     Production
    TNS for 32-bit Windows: Version 9.2.0.5.0 - Production
    NLSRTL Version 9.2.0.5.0 - Production
    Can you please guide me on this
    Thanks
    Ananda
    Edited by: Ananda on Nov 13, 2008 3:49 PM
    Edited by: Ananda on Nov 13, 2008 8:56 PM

    Hi ,
    Thanks for ur reply....
    I am getting an Error as Missing Keyword and points to the WHERE in the update statement ..............
    Am i doin anything wrong here in the syntax ...........but if i do the same without the where statement in Update ....... Merge works fine but with wrong output
    Thanks
    Ananda
    Edited by: Ananda on Nov 13, 2008 4:06 PM

  • Doubt   regarding   Oracle Database 10g Release 2 (10.2.0.1.0) installation

    hello
    my pc has following configurtion
    256mb ram
    60gb hdd
    p4 2.4 ghz
    win xp pro sp2
    I want to know if my pc will be able to run " Oracle Database 10g Release 2 (10.2.0.1.0) " standard edition on it.
    <<http://www.oracle.com/technology/software/products/database/oracle10g/htdocs/10201winsoft.html>>
    I thought of increasing RAM, but it is not feasible.
    I know i could run oracle XE, but can my pc also run the standard edition.
    I could not find minimum hardware requirements for standard edition on this site.
    anyway, i will use it for sql and and other advanced concepts in RDBMS which i may learn during my course in database. so i prefer standard edition instead of XE
    any help greatly appreciated
    thanks in advance

    I suggest you not to doubt   regarding   Oracle Database 10g Release 2 (10.2.0.1.0) installation.
    It is not necessary. If you don't receive an answer within a reasonable amount of time you could edit your thread with whatever ( a period is enough) to raise it to the top once again.
    It becomes difficult for us to track duplicated threads and unnecessarily duplicates efforts.
    ~ Madrid.

  • Oracle 11g merge statement not working properly

    HI I have recently my oracle version to 11.2.0.3 -64 bit . My merge statement is geeting failied saying that invlid identfier at line number 18    
    MERGE INTO peer_index indx        USING staging.stg_peer_filing stg          ON (indx.peer_element_code = stg.fund_code                and indx.index_effective_date = trunc(stg.pricing_date))        WHEN MATCHED THEN UPDATE          SET indx.filing_date = trunc(stg.filing_date),            indx.reported_net_assets = stg.net_assets,            indx.active_flag = 'N',            indx.parent_index_code = NULL,            indx.update_datetime = systimestamp,            indx.last_update_user_id = user        WHEN NOT MATCHED THEN INSERT         (index_code, peer_element_code, filing_date, index_effective_date,          reported_net_assets, active_flag          )        VALUES         ((SELECT pe.index_code_prefix || to_char(stg.pricing_date,'MMRR')           FROM fi_benchmark.peer_element pe           WHERE pe.peer_element_code = stg.fund_code),          stg.fund_code, trunc(stg.filing_date), trunc(stg.pricing_date),          stg.net_assets, 'N'         );
    please help why this is happening .Same query works fine in 10g .

    which line is the line that has the error?
    merge INTO peer_index indx
    USING staging.stg_peer_filing stg
    ON (indx.peer_element_code = stg.fund_code AND indx.index_effective_date = Trunc
    (stg.pricing_date))
    WHEN matched THEN
      UPDATE SET indx.filing_date = Trunc(stg.filing_date),
                 indx.reported_net_assets = stg.net_assets,
                 indx.active_flag = 'N',
                 indx.parent_index_code = NULL,
                 indx.update_datetime = systimestamp,
                 indx.last_update_user_id = USER
    WHEN NOT matched THEN
      INSERT (index_code,
              peer_element_code,
              filing_date,
              index_effective_date,
              reported_net_assets,
              active_flag )
      VALUES ((SELECT pe.index_code_prefix
                      || To_char(stg.pricing_date, 'MMRR')
               FROM   fi_benchmark.peer_element pe
               WHERE  pe.peer_element_code = stg.fund_code),
              stg.fund_code,
              Trunc(stg.filing_date),
              Trunc(stg.pricing_date),
              stg.net_assets,
              'N' );

  • Can sql merge statement be used in a batch (oracle 10g)?

    Hello,
    I am trying to insert into an oracle table multiple rows of values selected from a web page. Can I use a merge statement as a preparedStatement to avoid inserting duplicate records?
    Does anybody have any examples they would like to share?
    Any suggestions are greatly appreciated.
    Thank you,
    Logan

    I've implemented this by batch inserting into a temp table then running a merge then dropping the temp table.
    public void mergeMethod() {
            final String createsql = "CREATE TABLE temp (a INTEGER, b INTEGER, c INTEGER)";
            final String insertsql = "INSERT INTO temp (a, b, c) VALUES (?,?,?)";
            final String mergesql = "MERGE INTO my_table A " +
               "USING temp B ON (A.a = B.a AND A.b = B.b) " +
               "WHEN MATCHED THEN UPDATE SET A.c = B.c " +
               "WHEN NOT MATCHED THEN INSERT (A.id, A.a, A.b, A.c) " +
               "VALUES (my_seq.Nextval,B.a,B.b,B.c)";
            final String dropsql = "DROP TABLE temp";
         Connection conn = null;
         Statement cs = null;
         Statement ms = null;
         Statement ds = null;
         PreparedStatement ps = null;
         boolean retValue = false;
         try {
              conn = getConnection();
              conn.setAutoCommit(false);
              cs = conn.createStatement();
              ms = conn.createStatement();
              ds = conn.createStatement();
              ps = conn.prepareStatement(insertsql);
              for (int i=0; i< 10; i++){
                   ps.setInt(1, i);
                   ps.setInt(2, i+1);
                   ps.setInt(3, i+2);
                   ps.addBatch();
              // create temp table
              cs.execute(createsql);
              // execute in batch
              final int updateCount[] = ps.executeBatch();
              // merge the two tables
              ms.execute(mergesql);
              // drop the temp table
              ds.execute(dropsql);
              conn.commit();
              System.out.println("Rows is updated: " + updateCount.length);
         } catch (final SQLException e) {
              if (conn != null) {
                  conn.rollback();
              throw e;
         } finally {
              if (ps != null) {
                  ps.close();
              if (cs != null) {
                  cs.close();
              if (ms != null) {
                  ms.close();
              if (ds != null) {
                  ds.close();
              if (conn != null) {
                  conn.close();
    }

  • Issue with Oracle Merge statements (PL/SQL: ORA-00913: too many values)

    Hi All,
    I am using the below merge statement and I am getting too many rows issues when I am compiling.
    BEGIN
    FOR te_rec IN ( SELECT /*+ parallel(ts,4) */ te.dtv_acct_num FROM telcos_eligible te, telcos_setup ts, telcos_partners tp
    WHERE tp.telcos_name = UPPER((p_telcos_name))
    AND ts.partner_id = tp.partner_id
    AND te.ts_id = ts.ts_id ) LOOP
    MERGE INTO tcs_accounts
    USING (
    SELECT /*+ DRIVING_SITE(a) */account_id, a.subscriber_id, status, account_type FROM account@tcs_to_paris a WHERE a.subscriber_id = te_rec.dtv_acct_num
    ) paris_accounts
    ON (tcs_accounts.subscriber_id = paris_accounts.subscriber_id)
    WHEN MATCHED THEN
    UPDATE SET
    account_type = paris_accounts.account_type,
    subscriber_id = paris_acounts.subscriber_id,
    status = paris_accounts.status
    WHEN NOT MATCHED THEN
    INSERT(account_id, subscriber_id, status_account_type)
    VALUES(paris_accounts.account_id, paris_accounts.subscriber_id, paris_accounts.status, paris_accounts.account_type);
    END LOOP;
    END;
    Can you let me know what is the issue here.
    Thanks,
    MK.

    Hi,
    Maddy wrote:
    ... WHEN NOT MATCHED THEN
    INSERT(account_id, subscriber_id, status_account_type)
    VALUES(paris_accounts.account_id, paris_accounts.subscriber_id, paris_accounts.status, paris_accounts.account_type);This is one of the many times when a little formatting can really help you. Anybody can forget a column (or have an extra one, or type a _ when they mean ,) but if you write code like this
    INSERT (               account_id,                 subscriber_id,                                  status_account_type)
    VALUES (paris_accounts.account_id,  paris_accounts.subscriber_id,  paris_accounts.status,  paris_accounts.account_type);you might spot the error yourself.
    Always format your code. When you post any formatted text on thsi site, type these 6 characters:
    \(small letters only, inside curly brackets) before and after formatted text, to preserve spacing.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

  • Help needed in the Merge Statement

    Hi All,
    I am using MERGE statement in my program. I want to maintain the log for the duplicate reords mean maintain the log for those reocrds which are updated in the merge statement.
    Can any one help me in this that how can i maintain the log?
    Thanks for your help in advance.
    kind Regards,

    http://asktom.oracle.com/pls/asktom/f?p=100:11:0::::P11_QUESTION_ID:35615502072484

  • Locking in Merge Statement

    Hi All,
    I am using merge statement to insert and update rows. The merge statement takes a row level exclusive lock
    Suppose the select statement returns 1 Million records does
    1) The merge statement first tries to lock all the affected rows and then update / insert records.
    OR
    2) The merge statement aquires lock on an incremental basis as returned by the select statement.

    The merge works just like an insert or update statement in that locks are acquired "on an incremental basis", but as of the timestamp the merge began. When Oracle detects that another session has updated a row in the meantime, then it re-executes the entire merge statement as of that new timestamp. It is sometimes referred to as "write consistency".
    Here is a good Asktom thread on this topic: http://asktom.oracle.com/pls/asktom/f?p=100:11:1694097844551766::::P11_QUESTION_ID:11504247549852
    Regards,
    Rob.

Maybe you are looking for