Returning clause in MERGE statement

Hi ,
I'm using Oracle 10g Version
I tried the below code using UPDATE  with Returning Clause & MERGE with Returning Clause .
I found NO errors while working with UPDATE statement  . The following is the code with UPDATE statement
DECLARE
   TYPE empno_list IS TABLE OF emp.empno%TYPE;
   vempno_list   empno_list;
BEGIN
      UPDATE emp
         SET comm = 11
       WHERE deptno IN (SELECT deptno FROM dept)
   RETURNING empno
        BULK COLLECT INTO vempno_list;
   FOR i IN vempno_list.FIRST .. vempno_list.LAST
   LOOP
      DBMS_OUTPUT.put_line ('Values of EMP ' || vempno_list (i));
   END LOOP;
END;  
But getting the error PL/SQL: ORA-00933: SQL command not properly ended  when working with MERGE Statement
declare
type empno_list  is  table of emp.empno%type;
vempno_list empno_list;
begin               
   merge into emp tgt
      using dept src
        on (src.deptno =tgt.deptno)
        when matched then
         update set tgt.comm=12
       returning tgt.empno bulk collect into vempno_list ;
        for i in vempno_list.first .. vempno_list.last loop
                dbms_output.put_line('Values of EMP '||vempno_list(i) ) ;
        end loop;
end; 
Please  suggest me

Probably because the RETURNING INTO clause doesn't belong to MERGE statement. It's available only for INSERT, UPDATE and DELETE. Here is the quote from Oracle Documentation:
The static RETURNING INTO clause belongs to a DELETE, INSERT, or UPDATE statement. The dynamic RETURNING INTO clause belongs to an EXECUTEIMMEDIATE statement.
And here's the link.
RETURNING INTO Clause
Hope it helps.
Ishan

Similar Messages

  • HOW TO USE RETURNING CLAUSE USING MERGE

    Hello All,
    Is there a way to find out the rows that got inserted into a table using the merge statement.
    Merge statement is given below. I need to know what rows were inserted when this query got executed.
    MERGE INTO PR P USING
         (SELECT A.ID, A.NAME, A.PENSION FROM MEMBER_PROFILE A, PROFILE B WHERE A.ID=B.ID)RES
         ON P.PENSION = RES.PENSION
    WHEN MATCHED THEN
         UPDATE SET P.MOD_DATE= SYSDATE
    WHEN NOT MATCHED THEN
         INSERT(P.ID, P.NAME, P.PENSION)
         VALUES(RES.ID, RES.NAME, RES.PENSION)

    However there are some solutions
    So if you really need to track this data you can play with something like this:
    Let’s try to add columns row_trunsaction_id (and may be transaction_type) to you merged table. Consider you get a new transaction id before a merge and insert id and type in your table if is new record.
    You also can use Date: you should have row creation date and row update date
    When insert, fresh creation date inserted, when update, update_date updated
    After all you may query this information right after transaction and put it in you log table.

  • MERGE statement without INSERT clause....is possible...?

    Hi everybody...
    MERGE statement without UPDATE or INSERT clause is possible or not
    I want to select from one table and update in another table. So i dont want insert statement and i want to do it in single query....possible solutions are requested.
    Thanks in advance
    pal

    Hi..
    Thanks for ur reply. For MERGE statement, we have to give UPDATE and INSERT clause. this MERGE statement works without INSERT or UPDATE clause.
    Why i am asking is, I want to select how many rows (count(*)) from table1 and based on this count, i have to update in table2
    Both tables r different and for select and for update where clauses are different. Both tables r totally different.
    I want to do it in single query, so i asked this is possible with MERGE statement without INSERT clause.
    Thanks for ur reply

  • Can we use where clause in Update on Merge statement?

    Hi All,
    I tried to execute the following Merge Query:
    When this query is executed without ‘Where clause’ in Update statement its working fine. When executed with ‘Where clause’ it throwing the following error:
    ORA-00905: missing keyword.
    Following is the sample query which I tried to execute:
    MERGE INTO TABLE_NAME
    USING (SELECT COLUMN FORM TABLES)
    ON (CONDITION)
    WHEN MATCHED THEN
    UPDATE SET
         COLUMN UPATES
    WHERE CONDITION -- Can we use where clause here?
    WHEN NOT MATCHED THEN
    INSERT
    INSERT VALUES;
    Can some one help on this?
    Thanks in advance.
    Darius

    Yes:
    SQL> drop table emp1;
    Table dropped.
    SQL> create table emp1 as select * from emp where deptno = 30;
    Table created.
    SQL> update emp1 set sal = sal*2;
    6 rows updated.
    SQL> commit;
    Commit complete.
    SQL> select ename,sal from emp1;
    ENAME             SAL
    ALLEN            3200
    WARD             2500
    MARTIN           2500
    BLAKE            5700
    TURNER           3000
    JAMES            1900
    6 rows selected.
    SQL> MERGE INTO emp1
      2  USING(select * from emp) emp
      3  ON (emp1.empno = emp.empno)
      4  WHEN MATCHED THEN
      5  UPDATE SET sal = emp.sal WHERE ename = 'TURNER'
      6  WHEN NOT MATCHED THEN
      7  INSERT(ename,sal) VALUES(emp.ename,emp.sal);
    9 rows merged.
    SQL> select ename,sal from emp1;
    ENAME             SAL
    ALLEN            3200
    WARD             2500
    MARTIN           2500
    BLAKE            5700
    TURNER 1500
    JAMES            1900
    SMITH             800
    JONES            2975
    CLARK            2450
    SCOTT            3000
    KING             5000
    ENAME             SAL
    ADAMS            1100
    FORD             3000
    MILLER           1300
    14 rows selected.
    SQL> SY.

  • Question on passing string values to Partition clause in a merge statement

    Hello All,
    I am using the below code to update specific sub-partition data using oracle merge statements.
    I am getting the sub-partition name and passing this as a string to the sub-partition clause.
    The Merge statement is failing stating that the specified sub-partition does not exist. But the sub-partition do exists for the table.
    We are using Oracle 11gr2 database.
    Below is the code which I am using to populate the data.
    declare
    ln_min_batchkey PLS_INTEGER;
    ln_max_batchkey PLS_INTEGER;
    lv_partition_name VARCHAR2 (32767);
    lv_subpartition_name VARCHAR2 (32767);
    begin
    FOR m1 IN ( SELECT (year_val + 1) AS year_val, year_val AS orig_year_val
    FROM ( SELECT DISTINCT
    TO_CHAR (batch_create_dt, 'YYYY') year_val
    FROM stores_comm_mob_sub_temp
    ORDER BY 1)
    ORDER BY year_val)
    LOOP
    lv_partition_name :=
    scmsa_handset_mobility_data_build.fn_get_partition_name (
    p_table_name => 'STORES_COMM_MOB_SUB_INFO',
    p_search_string => m1.year_val);
    FOR m2
    IN (SELECT DISTINCT
    'M' || TO_CHAR (batch_create_dt, 'MM') AS month_val
    FROM stores_comm_mob_sub_temp
    WHERE TO_CHAR (batch_create_dt, 'YYYY') = m1.orig_year_val)
    LOOP
    lv_subpartition_name :=
    scmsa_handset_mobility_data_build.fn_get_subpartition_name (
    p_table_name => 'STORES_COMM_MOB_SUB_INFO',
    p_partition_name => lv_partition_name,
    p_search_string => m2.month_val);
                        DBMS_OUTPUT.PUT_LINE('The lv_subpartition_name => '||lv_subpartition_name||' and lv_partition_name=> '||lv_partition_name);
    IF lv_subpartition_name IS NULL
    THEN
                             DBMS_OUTPUT.PUT_LINE('INSIDE IF => '||m2.month_val);
    INSERT INTO STORES_COMM_MOB_SUB_INFO T1 (
    t1.ntlogin,
    t1.first_name,
    t1.last_name,
    t1.job_title,
    t1.store_id,
    t1.batch_create_dt)
    SELECT t2.ntlogin,
    t2.first_name,
    t2.last_name,
    t2.job_title,
    t2.store_id,
    t2.batch_create_dt
    FROM stores_comm_mob_sub_temp t2
    WHERE TO_CHAR (batch_create_dt, 'YYYY') = m1.orig_year_val
    AND 'M' || TO_CHAR (batch_create_dt, 'MM') =
    m2.month_val;
    ELSIF lv_subpartition_name IS NOT NULL
    THEN
                        DBMS_OUTPUT.PUT_LINE('INSIDE ELSIF => '||m2.month_val);
    MERGE INTO (SELECT *
    FROM stores_comm_mob_sub_info
    SUBPARTITION (lv_subpartition_name)) T1
    USING (SELECT *
    FROM stores_comm_mob_sub_temp
    WHERE TO_CHAR (batch_create_dt, 'YYYY') =
    m1.orig_year_val
    AND 'M' || TO_CHAR (batch_create_dt, 'MM') =
    m2.month_val) T2
    ON (T1.store_id = T2.store_id
    AND T1.ntlogin = T2.ntlogin)
    WHEN MATCHED
    THEN
    UPDATE SET
    t1.postpaid_totalqty =
    (NVL (t1.postpaid_totalqty, 0)
    + NVL (t2.postpaid_totalqty, 0)),
    t1.sales_transaction_dt =
    GREATEST (
    NVL (t1.sales_transaction_dt,
    t2.sales_transaction_dt),
    NVL (t2.sales_transaction_dt,
    t1.sales_transaction_dt)),
    t1.batch_create_dt =
    GREATEST (
    NVL (t1.batch_create_dt, t2.batch_create_dt),
    NVL (t2.batch_create_dt, t1.batch_create_dt))
    WHEN NOT MATCHED
    THEN
    INSERT (t1.ntlogin,
    t1.first_name,
    t1.last_name,
    t1.job_title,
    t1.store_id,
    t1.batch_create_dt)
    VALUES (t2.ntlogin,
    t2.first_name,
    t2.last_name,
    t2.job_title,
    t2.store_id,
    t2.batch_create_dt);
    END IF;
    END LOOP;
    END LOOP;
    COMMIT;
    end;
    Much appreciate your inputs here.
    Thanks,
    MK.

    I've not used partitioning, but I do not see MERGE supporting a variable as a partition name in
    MERGE INTO (SELECT *
    FROM stores_comm_mob_sub_info
    SUBPARTITION (lv_subpartition_name)) T1
    USING ... I suspect it is looking for a partition called lv_subpartition_name.
    I also don't see why you need that partition name - the ON clause should be able to identify the partition's criteria.

  • Issue while using SUBPARTITION clause in the MERGE statement in PLSQL Code

    Hello All,
    I am using the below code to update specific sub-partition data using oracle merge statements.
    I am getting the sub-partition name and passing this as a string to the sub-partition clause.
    The Merge statement is failing stating that the specified sub-partition does not exist. But the sub-partition do exists for the table.
    We are using Oracle 11gr2 database.
    Below is the code which I am using to populate the data.
    declare
    ln_min_batchkey PLS_INTEGER;
    ln_max_batchkey PLS_INTEGER;
    lv_partition_name VARCHAR2 (32767);
    lv_subpartition_name VARCHAR2 (32767);
    begin
    FOR m1 IN ( SELECT (year_val + 1) AS year_val, year_val AS orig_year_val
    FROM ( SELECT DISTINCT
    TO_CHAR (batch_create_dt, 'YYYY') year_val
    FROM stores_comm_mob_sub_temp
    ORDER BY 1)
    ORDER BY year_val)
    LOOP
    lv_partition_name :=
    scmsa_handset_mobility_data_build.fn_get_partition_name (
    p_table_name => 'STORES_COMM_MOB_SUB_INFO',
    p_search_string => m1.year_val);
    FOR m2
    IN (SELECT DISTINCT
    'M' || TO_CHAR (batch_create_dt, 'MM') AS month_val
    FROM stores_comm_mob_sub_temp
    WHERE TO_CHAR (batch_create_dt, 'YYYY') = m1.orig_year_val)
    LOOP
    lv_subpartition_name :=
    scmsa_handset_mobility_data_build.fn_get_subpartition_name (
    p_table_name => 'STORES_COMM_MOB_SUB_INFO',
    p_partition_name => lv_partition_name,
    p_search_string => m2.month_val);
                        DBMS_OUTPUT.PUT_LINE('The lv_subpartition_name => '||lv_subpartition_name||' and lv_partition_name=> '||lv_partition_name);
    IF lv_subpartition_name IS NULL
    THEN
                             DBMS_OUTPUT.PUT_LINE('INSIDE IF => '||m2.month_val);
    INSERT INTO STORES_COMM_MOB_SUB_INFO T1 (
    t1.ntlogin,
    t1.first_name,
    t1.last_name,
    t1.job_title,
    t1.store_id,
    t1.batch_create_dt)
    SELECT t2.ntlogin,
    t2.first_name,
    t2.last_name,
    t2.job_title,
    t2.store_id,
    t2.batch_create_dt
    FROM stores_comm_mob_sub_temp t2
    WHERE TO_CHAR (batch_create_dt, 'YYYY') = m1.orig_year_val
    AND 'M' || TO_CHAR (batch_create_dt, 'MM') =
    m2.month_val;
    ELSIF lv_subpartition_name IS NOT NULL
    THEN
                        DBMS_OUTPUT.PUT_LINE('INSIDE ELSIF => '||m2.month_val);
    MERGE INTO (SELECT *
    FROM stores_comm_mob_sub_info
    SUBPARTITION (lv_subpartition_name)) T1 --> Issue Here
    USING (SELECT *
    FROM stores_comm_mob_sub_temp
    WHERE TO_CHAR (batch_create_dt, 'YYYY') =
    m1.orig_year_val
    AND 'M' || TO_CHAR (batch_create_dt, 'MM') =
    m2.month_val) T2
    ON (T1.store_id = T2.store_id
    AND T1.ntlogin = T2.ntlogin)
    WHEN MATCHED
    THEN
    UPDATE SET
    t1.postpaid_totalqty =
    (NVL (t1.postpaid_totalqty, 0)
    + NVL (t2.postpaid_totalqty, 0)),
    t1.sales_transaction_dt =
    GREATEST (
    NVL (t1.sales_transaction_dt,
    t2.sales_transaction_dt),
    NVL (t2.sales_transaction_dt,
    t1.sales_transaction_dt)),
    t1.batch_create_dt =
    GREATEST (
    NVL (t1.batch_create_dt, t2.batch_create_dt),
    NVL (t2.batch_create_dt, t1.batch_create_dt))
    WHEN NOT MATCHED
    THEN
    INSERT (t1.ntlogin,
    t1.first_name,
    t1.last_name,
    t1.job_title,
    t1.store_id,
    t1.batch_create_dt)
    VALUES (t2.ntlogin,
    t2.first_name,
    t2.last_name,
    t2.job_title,
    t2.store_id,
    t2.batch_create_dt);
    END IF;
    END LOOP;
    END LOOP;
    COMMIT;
    end;
    Much appreciate your inputs here.
    Thanks,
    MK.
    (SORRY TO POST THE SAME QUESTION TWICE).
    Edited by: Maddy on May 23, 2013 10:20 PM

    Duplicate question

  • ORA-00904 in Merge statement

    I encountered with ORA-00904 in Merge statement. I fixed the error but I don't know why. Would you please help me explain it? Thanks in advance. The following is the detail description of my question.
    I have two tables TBL_A<col1 integer,col2 integer> TBL_B<col1 integer,col2 integer> and an anonymous block to test executed in Oracle 10gR2.
    DECLARE
    V_NUM INTEGER;
    BEGIN
    V_NUM := 1;
    /*merge I it's okay.the function of merge seems meaningless, please pay attention to its grammar*/
    MERGE INTO TBL_A A
    USING (SELECT V_NUM N, COL1, COL2 FROM TBL_B) B
    ON (A.COL1 = B.N)
    WHEN MATCHED THEN
    UPDATE SET A.COL2 = B.COL2;
    /*merge II*/
    /*ora-00904*/
    MERGE INTO TBL_A A
    USING (SELECT V_NUM, COL1, COL2 FROM TBL_B) B
    ON (A.COL1 = V_NUM)
    WHEN MATCHED THEN
    UPDATE
    SET A.COL2 = B.COL2;
    /*merge III is okay*/
    MERGE INTO TBL_A A
    USING (SELECT COL1, COL2 FROM TBL_B) B
    ON (A.COL1 = V_NUM)
    WHEN MATCHED THEN
    UPDATE
    SET A.COL2 = B.COL2;
    COMMIT;
    END;
    I traced the 904 error and it seems the point is in the binding of variable V_NUM. But I don't know the exact reason. I think maybe it relates with the parse of PL/SQL. Would someone please help me or give me some hints?

    hi,
    When you saye,
       MERGE INTO TBL_A A
        USING (SELECT V_NUM,
                      COL1,
                      COL2
                 FROM TBL_B) B
           ON (A.COL1 = V_NUM)
       WHEN MATCHED
       THEN
          UPDATE SET A.COL2 = B.COL2;
    In the above for ON (A.COL1 = V_NUM)
    oracle treats v_num as a variable in the procedure rather than v_num returned from using clause.
    So you need to alias that.
    MERGE INTO TBL_A A
        USING (SELECT V_NUM as somecol,
                      COL1,
                      COL2
                 FROM TBL_B) B
           ON (A.COL1 = b.somecol)
       WHEN MATCHED
       THEN
          UPDATE SET A.COL2 = B.COL2;Edited by: Ganesh Srivatsav on May 12, 2011 11:42 AM
    Added alias after peter pointed out for variable in the using.

  • Bogus Invalid Object in MERGE Statement

    Let me begin by saying that I have been working with MERGE since its inception, and I am familiar with the fundamental gotcha's. This problem is more inexplicable. (It's one of those things that I expect, when someone explains it, will be a DOH! moment.)
    I am building a one-time conversion script to merge an existing User table with a new User table. Since I am only in the development mode, I didn't want to modify the true table yet. So I made a copy of the table to work with, using the following familiar
    syntax.
    SELECT *
    INTO uam.User2
    FROM uam.[User]
    Imagine my surprise when the MERGE statement refused to recognize uam.User2 - although it recognizes uam.[User] just fine.
    In the interests of competeness, here is the MERGE Statement in question.
    MERGE  uam.[User2]
    as tgt
    USING (SELECT
    UserID
    ,FirstName
    ,LastName
    ,CompanyID
    ,AuthenticationID
    ,isActive
    ,PrimaryEmailID
    ,CreatedByUserName
    ,CreatedByDtim
    ,@User
    _User
    ,GETDATE()
    _GETDATE
    FROM #User
    ) as src
      ON tgt.UserID = (src.UserID * -1)
    WHEN NOT MATCHED
    THEN
    INSERT
    (FirstName
    ,LastName
    ,CompanyID
    ,AuthenticationID
    ,isActive
    ,PrimaryEmailID
    ,CreatedByUserName
    ,CreatedByDtim
    ,LastUpdatedUserName
    ,LastUpdatedDtim
    VALUES
    (src.FirstName
    ,src.LastName
    ,src.CompanyID
    ,src.AuthenticationID
    ,src.isActive
    ,src.PrimaryEmailID
    ,src.CreatedByUserName
    ,src.CreatedByDtim
    ,_User
    ,_GETDATE
    OUTPUT INSERTED.UserID
    ,tgt.UserID
    INTO #UserMapping;
    The procedure refuses to run, flagging the tgt.UserID as 
    Msg 4104, Level 16, State 1, Line 140
    The multi-part identifier "tgt.UserID" could not be bound.
    SSMS also flags the uam.[User2] on the MERGE line as "Invalid object name 'uam.User2'" on mouse-over.
    A few notes:
    I have a SELECT * FROM uam.User2 immediately before this MERGE, and it works just fine. And yes, it returns a UserID column.
    If I change the name from uam.User2 to uam.[User], it works just fine.
    I know the JOIN is a little strange (I really wanted just an INSERT where I could see the original UserID and the newly inserted UserID together, and INSERT will not let me OUTPUT directly from a table - hence the MERGE), but I also tried it with a straight-up
    tgt.UserID = src.UserID. Nothing changed about the errors.
    I also went back and re-created the uam.User2 table directly from the code that built uam.[User]. Nothing changed.
    I'm flummoxed. This has all the earmarks of a "well-that-was-dumb" coding error, but for the life of me I cannot see what would change between using these two tables, since one is a copy of the other...
    Any insight would be much appreciated!
    Duncan Davenport

    OK, I have it.
    DOH!  (told ya)
    So, while intellisense (typically) flags this table as not existing, that's just Intellisense doing the nonsense it always does. This obfuscated the ACTUAL error - which was the wrong schema defined in the output clause. The error itself pointed at the wrong
    line (nothing new there either). Once I fixed the OUTPUT clause, everything worked as expected - although SSMS is still putting squiggly red lines under everything that is working anyway. Yeah, we've all seen THAT behavior - no big deal.
    Anyway, that's the answer. It's magic - in that the error messages specialize in misdirection :)...
    Closing this. (I wonder if I get credit for answering my own question?)

  • Performance problem with MERGE statement

    Version : 11.1.0.7.0
    I have an insert statement like following which is taking less than 2 secs to complete and inserts around 4000 rows:
    INSERT INTO sch.tab1
              (c1,c2,c3)
    SELECT c1,c2,c3
       FROM sch1.tab1@dblink
      WHERE c1 IN (SELECT c1 FROM sch1.tab2@dblink);I wanted to change it to a MERGE statement just to avoid duplicate data. I changed it to following :
    MERGE INTO sch.tab1 t1
    USING (SELECT c1,c2,c3
       FROM sch1.tab1@dblink
      WHERE c1 IN (SELECT c1 FROM sch1.tab2@dblink) t2
    ON (t1.c1 = t2.c1)
    WHEN NOT MATCHED THEN
    INSERT (t1.c1,t1.c2,t1.c3)
    VALUES (t2.c1,t2.c2,t2.c3);The MERGE statement is taking more than 2 mins (and I stopped the execution after that). I removed the WHERE clause subquery inside the subquery of the USING section and it executed in 1 sec.
    If I execute the same select statement with the WHERE clause outside the MERGE statement, it takes just 1 sec to return the data.
    Is there any known issue with MERGE statement while implementing using above scenario?

    riedelme wrote:
    Are your join columns indexed?
    Yes, the join columns are indexed.
    You are doing a remote query inside the merge; remote queries can slow things down. Do you have to select all thr rows from the remote table? What if you copied them locally using a materialized view?Yes, I agree that remote queries will slow things down. But the same is not happening while select, insert and pl/sql. It happens only when we are using MERGE. I have to test what happens if we use a subquery refering to a local table or materialized view. Even if it works, I think there is still a problem with MERGE in case of remote subqueries (atleast till I test local queries). I wish some one can test similar scenarios so that we can know whether it is a genuine problem or some specific problem from my side.
    >
    BTW, I haven't had great luck with MERGE either :(. Last time I tried to use it I found it faster to use a loop with insert/update logic.
    Edited by: riedelme on Jul 28, 2009 12:12 PM:) I used the same to overcome this situation. I think MERGE needs to be still improved functionally from Oracle side. I personally feel that it is one of the robust features to grace SQL or PL/SQL.

  • 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 ;

  • Help needed in MERGE statement

    Hi,
    I am new to PL/SQL, I want to update a table called "final_test" based on the below query result.
    1. I want to check whether that particular record is present or not in my "final_test" table.
    2. If its present in the "final_test" table and the process_status got changed then I want to update that alone in my "final_test" table.
    3. If its not present then I want to insert that record into my "final_test" table.
    Basically I am retrieving the report and its status for a particular date.
    select
    b.id,
    a.name,
    a.t_name,
    c.process_status,
    c.time_process
    from rep_tab_map a, j_tab_map b, proc_status c
    where a.t_name=b.t_name
    and b.id=c.id (+)
    and trunc(c.date_start)=trunc(sysdate -1)
    group by a.name,b.id,c.process_status,c.time_process,a.t_name
    order by 2
    I thought of using Merge statement but i am not sure what i have to use in ":USING" and "ON" clause.
    Please help me with MERGE or with someother way.
    Thanks

    Assuming final_test has same structure as select list in your query:
    merge
      into final_test a
      using (
             select  b.id,
                     a.name,
                     a.t_name,
                     c.process_status,
                     c.time_process
               from  rep_tab_map a,
                     j_tab_map b,
                     proc_status c
               where a.t_name=b.t_name
                 and b.id=c.id(+)
                 and trunc(c.date_start)=trunc(sysdate -1)
               group by a.name,b.id,c.process_status,c.time_process,a.t_name
            ) b
      on (b.id = a.id)
      when matched then update set a.name = case a.process_status
                                              when b.process_status then a.name
                                              else b.name
                                            end,
                                   a.t_name = case a.process_status
                                                when b.process_status then a.t_name
                                                else b.t_name
                                              end,
                                   a.process_status = b.process_status,
                                   a.time_process = case a.process_status
                                                      when b.process_status then a.time_process
                                                      else b.time_process
                                                    end
      when not matched then insert(
                                   a.id,
                                   a.name,
                                   a.t_name,
                                   a.process_status,
                                   a.time_process
                            values(
                                   b.id,
                                   b.name,
                                   b.t_name,
                                   b.process_status,
                                   b.time_process
    /SY.

  • RETURN Clause in IF...ELSE Condition in PL/SQL Block

    Hi
    Could you please explain me the importance of a RETURN Clause in IF..ELSE Condition in PL/SQL Block with
    an example.
    Regards
    Nakul.V

    Hi,
    RETURN clause permits get out of the block. For more information you can see [Using the RETURN Statement|http://download.oracle.com/docs/cd/B19306_01/appdev.102/b14261/subprograms.htm#sthref1683]
    SET SERVEROUTPUT ON
    BEGIN
        IF 1 = 1 THEN
            dbms_output.put_line('Before return');
            RETURN;
        ELSE
            dbms_output.put_line('Else');
        END IF;
        dbms_output.put_line('After if');
    END;
    Connected to Oracle Database 10g Enterprise Edition Release 10.2.0.1.0
    Connected as hr
    SQL>
    SQL> BEGIN
      2      IF 1 = 1 THEN
      3          dbms_output.put_line('Before return');
      4          RETURN;
      5      ELSE
      6          dbms_output.put_line('Else');
      7      END IF;
      8      dbms_output.put_line('After if');
      9  END;
    10  /
    Before return
    PL/SQL procedure successfully completed
    SQL> Regards,
    Edited by: Walter Fernández on Dec 12, 2008 9:41 AM - Adding output
    Edited by: Walter Fernández on Dec 12, 2008 9:43 AM - Adding URL...

  • Using hints in MERGE statement

    i have a merge statement
    in that statement for select clause i am using index hints
    can i use it
    whether that will increase the performance or the reverse will happen
    any comments

    Hints should always be your last option. First try tune the sql without using any hints, most of the cases you will be ok. Over time when the table statistics(ex. rows) changes considerably hints may be negative impact.

  • Error in RETURNING clause in INSERT.....SELECT query

    Hi Friends
    I am having an error: "SQL stmt not properly ended" when i run the below code.
    Cant i fetch multiple values from the returning clause into a collection variable??
    insert into consumption__C
         (SITECODE, SALESORG, PRODFAM,CAMPCODE, CYEAR, MDATE, SYSENV, MTYPE, ACCOUNT__C, SUPPLIER__C,
    PRODUCT_PER_UNIT__C, PRODUCT__C, UNIT__C, AMOUNT_Y__C, VOLUME_Y__C, CURRENCY__C,SUPPLYMODE__C)
         select      ' '                    Sitecode,
                        ' '          Salesorg,
    ' '                    Prodfam,
                        ' '                    campcode,
                        ' '                    cyear,
                        pcurr_mig               MDATE,
                        psysenv                    SYSENV,
                        'NSet'                    MTYPE,                          
                        c.sitecode               Account__c,
                        ' '                    supplier__c,
                        ' '                    Product_per_unit__c,
                        c.material               Product__c,
                        ' '                    unit__c,
                        c.Amount           Amount_y__c,
                        ' '                    Volume__c,
                        'Euro'                    Currency__c,
                        ' '                    Supply_Mode__c
    from load_sales_customer_site c     returning c.customer_code bulk collect INTO temp;
    Kindly guide...... what is the problem!!
    Thanks in advance

    nice idea, but you can't use returning into with
    insert as select:
    SQL> select * from v$version;
    BANNER
    Oracle Database 10g Enterprise Edition Release 10.2.0.1.0 - 64bi
    PL/SQL Release 10.2.0.1.0 - Production
    CORE    10.2.0.1.0      Production
    TNS for Linux: Version 10.2.0.1.0 - Production
    NLSRTL Version 10.2.0.1.0 - Production
    SQL> create table exm(id primary key) as select object_id from all_objects
      2  where rownum <=100;
    Table created.
    SQL> declare
      2  type num_tbl is table of number;
      3   ll_num_tbl num_tbl;
      4   begin
      5   insert into exm(id)
      6  (select object_id * 100 from all_objects where rownum
      7   <=100) returning id into ll_num_tbl;
      8  end;
      9  /
    <=100) returning id into ll_num_tbl;
    ERROR at line 7:
    ORA-06550: line 7, column 9:
    PL/SQL: ORA-00933: SQL command not properly ended
    ORA-06550: line 5, column 2:
    PL/SQL: SQL Statement ignoredAmiel

  • Merge Statement in ABAP

    Dear Gurrus,
    i am having a trouble in using oracle merge statement in abap, the moment i use where clause in the bottom it  gives me an oracle error
    EXEC SQL.
      MERGE INTO SAP_GL_ACCOUNT@GETZDB a
      USING SKA1 b
        ON (A.gl_code= B.SAKNR)
      WHEN MATCHED THEN
        UPDATE SET a.posting_block =  B.XSPEB,
                   a.locked        =  B.XSPEA,
                   A.BALANCE_SHEET =  B.XBILK
         WHEN NOT MATCHED THEN
           insert   (gl_code,
                     DESCRIPTION,
                     posting_block,
                     locked,
                     balance_sheet)
          VALUES (b.SAKNR,'shadab',B.XSPEB,B.XSPEA,B.XBILK)
          where b. mandt = 950      I am talking about this line
             ENDEXEC.
    the Moment  i include WHERE clause in the botton before ENDEXEC it generates as error
    " Database error text........: "ORA-00904: "A3"."MANDT": invalid  identifier#ORA-02063: preceding line from GETZDB".
    although its a basic feature of Oracle to inclue where clauses in insert or update in merge, but here it is generating an error.

    Hello Shadab,
    As per my understanding of this oracle native sql code.
    everything is fine except the use of direct value i.e 950 .
    System is not able to process this value .
    This normally happens even in normal abap sql statements also.
    The better solution could be to declare a variable with the
    same data type as "mandt" and then pass this "950" value into that
    variable and then use this variable in the where clause instead of directly
    passing the value.
    i.e data:l_var type mandt vlaue '950'.
    The other option could be to use the same hard coded
    value but use this value in the where clause in quotations i.e.,
    '950' instead of 950.
    I hope this would solve your purpose, If not please reply me back.
    thanks,
    M.Naveen Kumar.

Maybe you are looking for

  • SXMB_MONI : Scheduled

    when i am doing a file to IDOC scenario.....in sxmb_moni i see the status as scheduled... how to see that its scheduled or stuck in a  queue Edited by: Harsha reddy on Jun 25, 2008 6:15 PM

  • XSD Diagram to image file

    Hi there, Does anyone know if it is possible to get the graphical representation of an XSD into an image format such as BMP, JPG or PNG so that it can then be embedded into documentation (e.g. Word)

  • Linking my Htmldb app to an existing website

    I would like to put my htmldb app onto my existing website under a different section eg. www.myweb.com/development/htmldb Is this possible? My current website uses servlets and 9IAS

  • Autocad work on mac os lion is slower compared to window

    i use auto cad on a daily bases. i also use cad on windows system. on mac the cad works a little a slower. mostly in zoom and pan command.

  • Materials for Dilog Programming

    Hi Guys, I am looking for Dilog Programming materials to learn dilog programming. As i am new to this topic please suggest me which are all the books n materials needed to learn dilog programming. Regards, ABAPer