Using Delete in Merge Statement

As merge statement inserts and updates the target data related to the source data but what if the target table contains some additional rows. I mean now both the target table and source tables are not the same. How to do it ?

mshamirtaloo wrote:
As merge statement inserts and updates the target data related to the source data but what if the target table contains some additional rows. I mean now both the target table and source tables are not the same. How to do it ?Well, there's nothing to say that the source and target need to be 'the same' so really not sure what you're asking.
As of Oracle 10 the MERGE command allows for insert, update and delete operations.
http://download.oracle.com/docs/cd/E11882_01/server.112/e10592/statements_9016.htm#SQLRF01606

Similar Messages

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

  • How to use Inner join of table as Source in Merge statement in SQL

    Hi All,
        I am trying to make source as multiple tables output using Join while coding there is no any syntax error but when i am executing this statement is giving following error
    Following is the query 
    Merge Into EmpDept Target
    Using (select E.Address,e.Design,e.EmailId,e.EmpId,e.Ename,e.ManagerId, e.Salary,D.DeptId,D.DeptName,D.Location from Employee E Inner join Dept D on E.DeptId=D.DeptId )As Source (Address,Design,EmailId,EmpId,EName,ManagerId,Salary,DeptId,DeptName,Location)
    On Source.EmpId=Target.EmpId
    when not matched then
    Insert (Target.Address,Target.Design,Target.EmailId,Target.EmpId,Target.Ename,Target.ManagerId, Target.Salary,Target.DeptId,Target.DeptName,Target.Location)
    values
    (Address,Design,EmailId,EmpId,EName,ManagerId, Salary,DeptId,DeptName,Location)
    When matched then 
    Update set Target.Address = Source.Address ,Target.Design = Source.Design,Target.EmailId      = Source.EmailId     ,Target.Ename       = Source.Ename      ,Target.ManagerId = Source.ManagerId , Target.Salary        = Source.Salary       ,Target.DeptId      = Source.DeptId      ,Target.DeptName = Source.DeptName ,Target.Location    = Source.Location;
    This is error while executing the above merge statement 
    The insert column list used in the MERGE statement cannot contain multi-part identifiers. Use single part identifiers instead.
    Please suggest me where i am wrong.. 
    Niraj Sevalkar

    MERGE INTO EmpDept Target
    Using (SELECT E.Address,
    e.Design,
    e.EmailId,
    e.EmpId,
    e.Ename,
    e.ManagerId,
    e.Salary,
    D.DeptId,
    D.DeptName,
    D.Location
    FROM Employee E
    INNER JOIN Dept D
    ON E.DeptId = D.DeptId) AS Source (Address, Design, EmailId, EmpId, EName, ManagerId, Salary, DeptId, DeptName, Location)
    ON Source.EmpId = Target.EmpId
    WHEN NOT matched THEN
    INSERT (Address,
    Design,
    EmailId,
    EmpId,
    Ename,
    ManagerId,
    Salary,
    DeptId,
    DeptName,
    Location)
    VALUES (Address,
    Design,
    EmailId,
    EmpId,
    EName,
    ManagerId,
    Salary,
    DeptId,
    DeptName,
    Location)
    WHEN matched THEN
    UPDATE SET Address = Source.Address,
    Design = Source.Design,
    EmailId = Source.EmailId,
    Ename = Source.Ename,
    ManagerId = Source.ManagerId,
    Salary = Source.Salary,
    DeptId = Source.DeptId,
    DeptName = Source.DeptName,
    Location = Source.Location;

  • Automatic Parallelism causes Merge statement to take longer.

    We have a problem in a new project as part of the ETL load into the Oracle datawarehouse we perform a merge statement to update rows in a global temporary table then load
    the results into a permanant table, when testing with automatic parallel execution enabled the plan changes and the merge never finishes and consumes vast amounts of resources.
    The database version is:-
    Database version :11.2.0.3
    OS: redhat 64bit
    three node rac 20 cores per node
    when executing serially the query response is typically similar to the following:
    MERGE /*+ gather_plan_statistics no_parallel */ INTO T_GTTCHARGEVALUES USING
      (SELECT
      CASTACCOUNTID,
      CHARGESCHEME,
      MAX(CUMULATIVEVALUE) AS MAXMONTHVALUE,
      MAX(CUMULATIVECOUNT) AS MAXMONTHCOUNT
    FROM
      V_CACHARGESALL
    WHERE
      CHARGEDATE >= TRUNC(TO_DATE(:B1,'YYYY-MM-DD'),'MM')
      AND CHARGEDATE < TO_DATE(:B1,'YYYY-MM-DD')
    GROUP BY
       CASTACCOUNTID,
       CHARGESCHEME
    HAVING MAX(CUMULATIVECOUNT) IS NOT NULL ) MTOTAL
    ON
      (T_GTTCHARGEVALUES.CASTACCOUNTID=MTOTAL.CASTACCOUNTID AND
      T_GTTCHARGEVALUES.CHARGESCHEME=MTOTAL.CHARGESCHEME)
    WHEN MATCHED
    THEN UPDATE SET
      CUMULATIVEVALUE=CUMULATIVEVALUE+MTOTAL.MAXMONTHVALUE ,
      CUMULATIVECOUNT=CUMULATIVECOUNT+MTOTAL.MAXMONTHCOUNT;
    1448340 rows merged.
    select * from table(dbms_xplan.display_cursor(null,null,'ALLSTATS LAST')); 
    | Id  | Operation                       | Name              | Starts | E-Rows | A-Rows |   A-Time   | Buffers | Reads  |  OMem |  1Mem | Used-Mem |
    |   0 | MERGE STATEMENT                 |                   |      1 |        |      0 |00:03:08.43 |    2095K|    186K|       |       |          |
    |   1 |  MERGE                          | T_GTTCHARGEVALUES |      1 |        |      0 |00:03:08.43 |    2095K|    186K|       |       |          |
    |   2 |   VIEW                          |                   |      1 |        |   1448K|00:02:53.14 |     619K|    177K|       |       |          |
    |*  3 |    HASH JOIN                    |                   |      1 |      1 |   1448K|00:02:52.70 |     619K|    177K|   812K|   812K| 1218K (0)|
    |   4 |     VIEW                        |                   |      1 |      1 |    203 |00:02:51.26 |     608K|    177K|       |       |          |
    |*  5 |      FILTER                     |                   |      1 |        |    203 |00:02:51.26 |     608K|    177K|       |       |          |
    |   6 |       SORT GROUP BY             |                   |      1 |      1 |    480 |00:02:51.26 |     608K|    177K| 73728 | 73728 |          |
    |*  7 |        FILTER                   |                   |      1 |        |     21M|00:02:56.04 |     608K|    177K|       |       |          |
    |   8 |         PARTITION RANGE ITERATOR|                   |      1 |    392K|     21M|00:02:51.32 |     608K|    177K|       |       |          |
    |*  9 |          TABLE ACCESS FULL      | T_CACHARGES       |     24 |    392K|     21M|00:02:47.48 |     608K|    177K|       |       |          |
    |  10 |     TABLE ACCESS FULL           | T_GTTCHARGEVALUES |      1 |   1451K|   1451K|00:00:00.48 |   10980 |      0 |       |       |          |
    Predicate Information (identified by operation id):
       3 - access("T_GTTCHARGEVALUES"."CASTACCOUNTID"="MTOTAL"."CASTACCOUNTID" AND "T_GTTCHARGEVALUES"."CHARGESCHEME"="MTOTAL"."CHARGESCHEME")
       5 - filter(MAX("CUMULATIVECOUNT") IS NOT NULL)
       7 - filter(TRUNC(TO_DATE(:B1,'YYYY-MM-DD'),'fmmm')<TO_DATE(:B1,'YYYY-MM-DD'))
       9 - filter(("LOGICALLYDELETED"=0 AND "CHARGEDATE">=TRUNC(TO_DATE(:B1,'YYYY-MM-DD'),'fmmm') AND "CHARGEDATE"<TO_DATE(:B1,'YYYY-MM-DD')))removing the no_parallel hint results in the following, (this is pulled from the sql monitoring report and editied to remove the lines relating to individual parallel servers)
    I understand that the query is considered for parallel execution due to the estimated length of time it will run for and although the degree of parallleism seems excessive
    it is the default maximum for the server configuration, what we are tryig to understand is which statistics could be inacurate or missing and could cause this kind of problem.
    In this case we can add the no_parallel hint in the etl package as a workaround but would really liek to identify the root cause to avoid similar problems elsewhere.
    SQL Monitoring Report
    SQL Text
    MERGE INTO T_GTTCHARGEVALUES USING (SELECT CASTACCOUNTID, CHARGESCHEME, MAX(CUMULATIVEVALUE) AS MAXMONTHVALUE,
    MAX(CUMULATIVECOUNT) AS MAXMONTHCOUNT FROM V_CACHARGESALL WHERE CHARGEDATE >= TRUNC(TO_DATE(:B1,'YYYY-MM-DD'),'MM')
    AND CHARGEDATE < to_date(:B1,'YYYY-MM-DD')
    GROUP BY CASTACCOUNTID, CHARGESCHEME HAVING MAX(CUMULATIVECOUNT) IS NOT NULL ) MTOTAL
    ON (T_GTTCHARGEVALUES.CASTACCOUNTID=MTOTAL.CASTACCOUNTID AND
    T_GTTCHARGEVALUES.CHARGESCHEME=MTOTAL.CHARGESCHEME) WHEN MATCHED THEN UPDATE SET
    CUMULATIVEVALUE=CUMULATIVEVALUE+MTOTAL.MAXMONTHVALUE ,
    CUMULATIVECOUNT=CUMULATIVECOUNT+MTOTAL.MAXMONTHCOUNT
    Error: ORA-1013
    ORA-01013: user requested cancel of current operation
    Global Information
    Status              :  DONE (ERROR)
    Instance ID         :  1
    Session             :  XXXX(2815:12369)
    SQL ID              :  70kzttjbyyspt
    SQL Execution ID    :  16777216
    Execution Started   :  04/27/2012 09:43:27
    First Refresh Time  :  04/27/2012 09:43:27
    Last Refresh Time   :  04/27/2012 09:48:43
    Duration            :  316s
    Module/Action       :  SQL*Plus/-
    Service             :  SYS$USERS
    Program             :  sqlplus@XXXX (TNS V1-V3)
    Binds
    ========================================================================================================================
    | Name | Position |     Type     |                                        Value                                        |
    ========================================================================================================================
    | :B1  |        1 | VARCHAR2(32) | 2012-04-25                                                                          |
    ========================================================================================================================
    Global Stats
    ====================================================================================================================
    | Elapsed | Queuing |   Cpu   |    IO    | Application | Concurrency | Cluster  |  Other   | Buffer | Read | Read  |
    | Time(s) | Time(s) | Time(s) | Waits(s) |  Waits(s)   |  Waits(s)   | Waits(s) | Waits(s) |  Gets  | Reqs | Bytes |
    ====================================================================================================================
    |    7555 |    0.00 |    4290 |     2812 |        0.08 |          27 |      183 |      243 |     3M | 294K |   7GB |
    ====================================================================================================================
    SQL Plan Monitoring Details (Plan Hash Value=323941584)
    ==========================================================================================================================================================================================================
    | Id |             Operation             |       Name        |  Rows   | Cost  |   Time    | Start  | Execs |   Rows   | Read | Read  |  Mem  | Activity |                Activity Detail                |
    |    |                                   |                   | (Estim) |       | Active(s) | Active |       | (Actual) | Reqs | Bytes | (Max) |   (%)    |                  (# samples)                  |
    ==========================================================================================================================================================================================================
    |  0 | MERGE STATEMENT                   |                   |         |       |           |        |     1 |          |      |       |       |          |                                               |
    |  1 |   MERGE                           | T_GTTCHARGEVALUES |         |       |           |        |     1 |          |      |       |       |          |                                               |
    |  2 |    PX COORDINATOR                 |                   |         |       |        57 |     +1 |   481 |        0 |  317 |   5MB |       |     4.05 | latch: shared pool (40)                       |
    |    |                                   |                   |         |       |           |        |       |          |      |       |       |          | os thread startup (17)                        |
    |    |                                   |                   |         |       |           |        |       |          |      |       |       |          | Cpu (7)                                       |
    |    |                                   |                   |         |       |           |        |       |          |      |       |       |          | DFS lock handle (36)                          |
    |    |                                   |                   |         |       |           |        |       |          |      |       |       |          | SGA: allocation forcing component growth (14) |
    |    |                                   |                   |         |       |           |        |       |          |      |       |       |          | latch: parallel query alloc buffer (200)      |
    |  3 |     PX SEND QC (RANDOM)           | :TQ10003          |       1 | 19054 |           |        |       |          |      |       |       |          |                                               |
    |  4 |      VIEW                         |                   |         |       |           |        |       |          |      |       |       |          |                                               |
    |  5 |       FILTER                      |                   |         |       |           |        |       |          |      |       |       |          |                                               |
    |  6 |        SORT GROUP BY              |                   |       1 | 19054 |           |        |       |          |      |       |       |          |                                               |
    |  7 |         PX RECEIVE                |                   |       1 | 19054 |           |        |       |          |      |       |       |          |                                               |
    |  8 |          PX SEND HASH             | :TQ10002          |       1 | 19054 |           |        |   240 |          |      |       |       |          |                                               |
    |  9 |           SORT GROUP BY           |                   |       1 | 19054 |       246 |    +70 |   240 |        0 |      |       |  228M |    49.32 | Cpu (3821)                                    |
    | 10 |            FILTER                 |                   |         |       |       245 |    +71 |   240 |       3G |      |       |       |     0.08 | Cpu (6)                                       |
    | 11 |             HASH JOIN             |                   |       1 | 19054 |       259 |    +57 |   240 |       3G |      |       |  276M |     4.31 | Cpu (334)                                     |
    | 12 |              PX RECEIVE           |                   |      1M |     5 |       259 |    +57 |   240 |       1M |      |       |       |     0.04 | Cpu (3)                                       |
    | 13 |               PX SEND HASH        | :TQ10000          |      1M |     5 |         6 |    +56 |   240 |       1M |      |       |       |     0.01 | Cpu (1)                                       |
    | 14 |                PX BLOCK ITERATOR  |                   |      1M |     5 |         6 |    +56 |   240 |       1M |      |       |       |     0.03 | Cpu (1)                                       |
    |    |                                   |                   |         |       |           |        |       |          |      |       |       |          | PX Deq: reap credit (1)                       |
    | 15 |                 TABLE ACCESS FULL | T_GTTCHARGEVALUES |      1M |     5 |         7 |    +55 |  5486 |       1M | 5487 |  86MB |       |     2.31 | gc cr grant 2-way (3)                         |
    |    |                                   |                   |         |       |           |        |       |          |      |       |       |          | gc current block lost (7)                     |
    |    |                                   |                   |         |       |           |        |       |          |      |       |       |          | Cpu (7)                                       |
    |    |                                   |                   |         |       |           |        |       |          |      |       |       |          | db file sequential read (162)                 |
    | 16 |              PX RECEIVE           |                   |     78M | 19047 |       255 |    +61 |   240 |     801K |      |       |       |     0.03 | IPC send completion sync (2)                  |
    | 17 |               PX SEND HASH        | :TQ10001          |     78M | 19047 |       250 |    +66 |   240 |       3M |      |       |       |     0.06 | Cpu (5)                                       |
    | 18 |                PX BLOCK ITERATOR  |                   |     78M | 19047 |       250 |    +66 |   240 |       4M |      |       |       |          |                                               |
    | 19 |                 TABLE ACCESS FULL | T_CACHARGES       |     78M | 19047 |       254 |    +62 |  1016 |       4M | 288K |   6GB |       |    37.69 | gc buffer busy acquire (104)                  |
    |    |                                   |                   |         |       |           |        |       |          |      |       |       |          | gc cr block 2-way (1)                         |
    |    |                                   |                   |         |       |           |        |       |          |      |       |       |          | gc cr block lost (9)                          |
    |    |                                   |                   |         |       |           |        |       |          |      |       |       |          | gc cr grant 2-way (14)                        |
    |    |                                   |                   |         |       |           |        |       |          |      |       |       |          | gc cr multi block request (1)                 |
    |    |                                   |                   |         |       |           |        |       |          |      |       |       |          | gc current block 2-way (3)                    |
    |    |                                   |                   |         |       |           |        |       |          |      |       |       |          | gc current block 3-way (2)                    |
    |    |                                   |                   |         |       |           |        |       |          |      |       |       |          | gc current block busy (1)                     |
    |    |                                   |                   |         |       |           |        |       |          |      |       |       |          | gc current grant busy (2)                     |
    |    |                                   |                   |         |       |           |        |       |          |      |       |       |          | Cpu (58)                                      |
    |    |                                   |                   |         |       |           |        |       |          |      |       |       |          | latch: gc element (1)                         |
    |    |                                   |                   |         |       |           |        |       |          |      |       |       |          | db file parallel read (26)                    |
    |    |                                   |                   |         |       |           |        |       |          |      |       |       |          | db file scattered read (207)                  |
    |    |                                   |                   |         |       |           |        |       |          |      |       |       |          | db file sequential read (2433)                |
    |    |                                   |                   |         |       |           |        |       |          |      |       |       |          | direct path read (1)                          |
    |    |                                   |                   |         |       |           |        |       |          |      |       |       |          | read by other session (57)                    |
    ==========================================================================================================================================================================================================
    Parallel Execution Details (DOP=240 , Servers Allocated=480)
    Instances  : 3

    chris_c wrote:
    | Id  | Operation                       | Name              | Starts | E-Rows | A-Rows |   A-Time   | Buffers | Reads  |  OMem |  1Mem | Used-Mem |
    |*  9 |          TABLE ACCESS FULL      | T_CACHARGES       |     24 |    392K|     21M|00:02:47.48 |     608K|    177K|       |       |          |
    Based on the discrepancy between the estimated number of rows and the actual, and the below posted bind value of 2012-04-25 i'd first be checking if the statistics on T_CACHARGES are up to date.
    As a reference
    http://asktom.oracle.com/pls/asktom/f?p=100:11:0::::P11_QUESTION_ID:4399338600346902127
    So that would be my first avenue of exploration.
    Cheers,

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

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

  • 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

  • Error while using Merge statement

    Hi,
    Can any one please look at the merge statement and help me understand the error.Thanks in advance.
    MERGE /*+ APPEND */
    INTO intf_lpa_master m
    USING (SELECT std_district_student_id,
    std_grade_code,
    sub_test,
    test_date,
    performance_lvl_code,
    test_lang_code,
    v_student_id,
    v_test_id,
    v_lang_cd,
    v_plc,
    valid_test_date,
    -- school_year,
    -- school_id,
    valid_src_stu_id,
    test_code
    FROM intf_lpa_master_vw
    MINUS
    SELECT std_district_student_id,
    std_grade_code,
    sub_test,
    test_date,
    performance_lvl_code,
    test_lang_code,
    v_student_id,
    v_test_id,
    v_lang_cd,
    v_plc,
    valid_test_date,
    -- school_yr,
    -- school_id,
    valid_src_stu_id,
    test_code
    FROM intf_lpa_master
    WHERE active_flag = 'Y') v
    ON ( m.std_district_student_id = v.std_district_student_id
    AND m.sub_test = v.sub_test
    AND m.test_date = v.test_date)
    WHEN MATCHED
    THEN
    UPDATE SET m.std_grade_code = v.std_grade_code,
    m.performance_lvl_code = v.performance_lvl_code,
    m.test_lang_code = v.test_lang_code,
    m.active_flag = 'Y', -- if we are touching this record, it is to be active.
    m.error_message = NULL, -- refresh these, to properly reconsider records.
    m.create_date = SYSDATE,
    m.record_id = intf_lpa_master_seq.NEXTVAL,
    m.process_row = 'U',
    m.last_update_date = SYSDATE,
    m.last_update_user = 'PRE_PROCESS_LPA - UPDATE',
    -- m.job_id = c_run_id ,
    m.validation_step = NULL, -- refresh these, to properly reconsider records.
    m.v_student_id = v.v_student_id,
    m.v_test_id = v.v_test_id,
    m.v_lang_cd = v.v_lang_cd,
    m.v_plc = v.v_plc,
    m.valid_test_date = v.valid_test_date,
    -- m.school_year = v.schloo_year,
    -- m.school_id = v.school_id,
    m.valid_src_stu_id = v.valid_src_stu_id,
    m.test_code = v.test_code
    WHEN NOT MATCHED
    THEN
    INSERT (
    m.std_district_student_id,
    m.std_grade_code,
    m.sub_test,
    m.test_date,
    m.performance_lvl_code,
    m.test_lang_code,
    m.active_flag,
    m.error_message,
    m.create_date,
    m.record_id,
    m.process_row,
    m.last_update_date,
    m.last_update_user,
    -- m.job_id,
    m.validation_step,
    m.v_student_id,
    m.v_test_id,
    m.v_lang_cd,
    m.v_plc,
    m.valid_test_date,
    -- m. school_year,
    -- m. school_id,
    m.valid_src_stu_id,
    m.test_code)
    VALUES (
    v.std_district_student_id,
    v.std_grade_code,
    v.sub_test,
    v.test_date,
    v.performance_lvl_code,
    v.test_lang_code,
    'Y',
    NULL,
    SYSDATE,
    intf_lpa_master_seq.NEXTVAL,
    'I',
    SYSDATE,
    'PRE_PROCESS_LPA - INSERT',
    -- c_run_id,
    NULL,
    v.v_student_id,
    v.v_test_id,
    v.v_lang_cd,
    v.v_plc,
    v.valid_test_date,
    -- v. school_year,
    -- v. school_id,
    v.valid_src_stut_id,
    v.test_code);
    Error Message :
    ORA-06553 : PLS-306:wrong number or types of arguments in call to 'V'

    There are a couple of thngs wrong here. In the when matched insert column list, you cannot qualify the field name with the table alias. It should be just:
    insert (std_district_student_id, std_grade_code, sub_test ...)Are v_student_id, v_test_id, v_lang_cd, and v_plc really columns in the intf_lpa_master table? I am more used to seeing v_name as a variable naming convention than a column name, but I could be wrong.
    John

  • Error in merge statement when trying to impliment SCD type 2 using merge...

    Hi ,
    I'm trying to impliment SCD type 2 using Merge using below blog as reference but sime how it is erroring out with error
    http://www.made2mentor.com/2013/08/how-to-load-slowly-changing-dimensions-using-t-sql-merge/
    Msg 207, Level 16, State 1, Line 40
    Invalid column name 'Current'.
    Msg 207, Level 16, State 1, Line 38
    Invalid column name 'Current'.
    Msg 207, Level 16, State 1, Line 47
    Invalid column name 'Current'.
    Here is the code below...
    --Create Temporaty table to hold dimension records
    IF OBJECT_ID('tempdb..#DimVirtualQueue') IS NOT NULL
    DROP TABLE #DimVirtualQueue;
    CREATE TABLE #DimVirtualQueue
    ( [VQ_name] [varchar](50) NULL,
    [contact_type] [varchar](50) NULL,
    [center_node_id] [int] NULL,
    [sed_id] [datetime] NULL,
    [eed_id] [datetime] NULL,
    [insert_date] [datetime] NULL,
    [Current] [char](1) NOT NULL
    INSERT INTO #DimVirtualQueue(VQ_name, contact_type, center_node_id, sed_id, eed_id, insert_date,[Current] )
    SELECT VQ_name, contact_type, center_node_id, sed_id , eed_id,GETDATE(),'Y'
    FROM
    ( --Declare Source and Target tables.
    MERGE dbo.tblSwDM_dim_VQ_test AS TARGET
    --Source
    USING (SELECT
    RTRIM(LTRIM(Stage.RESOURCE_NAME)) AS VQ_name,
    'Unknown' AS contact_type,
    0 AS center_node_id,
    CONVERT(INT,CONVERT(VARCHAR(8),GMT_START_TIME,112)) AS sed_id,
    CONVERT(INT,CONVERT(VARCHAR(8),ISNULL(GMT_END_TIME,'2070-01-01'),112)) AS eed_id,
    GETDATE() AS insert_date
    FROM dbo.tblGenesys_stg_RESOURCE_ Stage
    WHERE resource_type = 'queue'
    AND resource_subtype = 'VirtualQueue'
    AND NOT EXISTS (SELECT 1 FROM dbo.tblSwDM_dim_VQ AS dim
    WHERE RTRIM(LTRIM(stage.RESOURCE_NAME)) = RTRIM(LTRIM(dim.vq_name))) ) SOURCE
    ON TARGET.VQ_name = SOURCE.VQ_name
    WHEN NOT MATCHED BY TARGET
    THEN
    INSERT ( VQ_name, contact_type, center_node_id, sed_id, eed_id, insert_date,[Current] )
    VALUES (SOURCE.VQ_name,SOURCE.contact_type,SOURCE.center_node_id,SOURCE.sed_id,SOURCE.eed_id,SOURCE.insert_date,'Y')
    WHEN MATCHED AND TARGET.[Current] = 'Y'
    AND EXISTS (
    SELECT SOURCE.VQ_name
    EXCEPT
    SELECT TARGET.VQ_name
    --Expire the records in target if exist in source.
    THEN UPDATE SET TARGET.[Current] = 'N',
    TARGET.[eed_id] = SOURCE.eed_id
    OUTPUT $Action ActionOut, SOURCE.VQ_name,SOURCE.contact_type,SOURCE.center_node_id,SOURCE.sed_id,SOURCE.eed_id) AS MergeOut
    WHERE MergeOut.ActionOut = 'UPDATE';
    --Insert data into dimension
    INSERT tblSwDM_dim_VQ_test
    SELECT VQ_name,contact_type,center_node_id,sed_id,eed_id,insert_date,[Current] FROM #DimVirtualQueue
    Any help to resolve issue is appreciated...
    Thanks,
    Vishal..

    You need to show the DDL of your target table: dbo.tblSwDM_dim_VQ_test.
    Do you have a column named [Current] in this table?

  • Problem using TAPI triggers and merge statement

    Hi,
    I use Designer tapi triggers on a table. When I try to execute a merge statement, I get the following error:
    ORA-06502: PL/SQL: numeric or value error: NULL index table key value.
    Is there a restriction when using TAPI triggers and merge statements that anyone is aware of?

    No restrictions on MERGE commands that I know of. I have, however, seen the TAPI give inexplicable ORA-06502 errors. It would help to know what line in which procedure or trigger gave the error. That information should have been in the error stack.

  • 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();
    }

  • Where should use Merge Statement in Form

    hi experts
    in Toad I am using this Merge statement , working accordingly.
    I want to use this merge statement in my form where can I use it.
    I created a Procedure in Form Named Proc_merge and call it when validate item of *:bankcode*
    PROCEDURE proc_merge IS
    BEGIN
    declare
    v_com varchar2(5000);
    BEGIN
    V_COM := ' 
    Merge into allvouchers trg
    using
    (select voucher_type,voucher_no,voucher_date,cheque_no,bank_code,narration,debit,credit from(
    select pv_voucher_type Voucher_type, pv_no Voucher_No, pv_date Voucher_date, Cheque_no, Acc_code Bank_code, Narration,Debit,Credit 
    from
                        (select a.pv_voucher_type,a.pv_no, a.pv_date, a.cheque_no, a.pv_gl_credit_code acc_code , b.ca_title,null Debit,
                                    a.pv_gl_credit_amount Credit, a.Pv_narration Narration
                                   from gl_pv a, ca_gl b where a.pv_gl_credit_Code = b.ca_code and a.pv_date > to_date (''30/06/2010'',''dd/mm/yyyy'')  
    union all 
                        select  a.pv_voucher_type,a.pv_voucher_no,a.pv_date,b.cheque_no,a.pv_acc_code,c.ca_title,a.pv_debit, Null credit,a.pv_desc
                        from payment_detail a, gl_pv b, ca_gl c
                        where a.pv_voucher_no = b.pv_no
                        and a.pv_date = b.pv_date
                        and a.pv_voucher_type = b.pv_voucher_type 
                        and pv_acc_code = c.ca_code and a.pv_debit > 0
                        and a.pv_date > to_date (''30/06/2010'',''dd/mm/yyyy'')     
    union all
                            select  a.pv_voucher_type, a.pv_voucher_no,a.pv_date, b.cheque_no, a.pv_acc_code, c.ca_title,
                        null ,a.pv_credit, a.pv_desc
                        from payment_detail a , gl_pv b , ca_gl c
                        where a.pv_voucher_no = b.pv_no
                        and a.pv_date = b.pv_date
                        and a.pv_acc_code = c.ca_code
                        and pv_credit >0 and a.pv_date > to_date (''30/06/2010'',''dd/mm/yyyy'')
    union all
                        select  a.pv_voucher_type, a.pv_no,pv_date,a.cheque_no , a.wht_debt_ac, b.ca_title , null, a.wht_amount, a.wht_narration 
                        from gl_pv a , ca_gl b where  a.wht_debt_ac = b.ca_code and  wht_amount > 0
                        and a.pv_date > to_date (''30/06/2010'',''dd/mm/yyyy'')
                        where acc_code = :bankcode
                        Union all 
    ---------------------   R.Voucher ----------------
    select a.rv_voucher_type, a.rv_no, a.rv_date, a.chequeno, b.rv_acc_code, a.rv_narration,b.rv_debit, b.rv_credit
    from gl_receipt a, receipt_detail b , ca_gl c
              where a.rv_no = b.rv_voucher_no
              and a.rv_date = b.rv_date
              and b.rv_acc_code = c.ca_code
              and b.rv_acc_code = :bankcode
              and a.rv_date > to_date (''30/06/2010'',''dd/mm/yyyy'')
    ----------------------- SRV --------------
    Union all
    select  a.vm_voucher_type ,a.vm_no ,a.vm_date,a.chequeno,b.vd_acc_code, b.vd_desc VNARRAION,
              b.vd_debit VDEBIT,b.vd_credit VCREDIT           
              from vouchermaster a, voucherdetail b , ca_gl c
              where a.vm_no= b.vd_no
              and a.vm_voucher_type = b.vm_voucher_type
              and a.vm_date = b.vm_date
              and b.vd_acc_code = c.ca_code
              and b.vd_acc_code  = :bankcode
              and a.vm_date > to_date (''30/06/2010'',''dd/mm/yyyy'')  
              and (a.show_voucher =''Y'' or Show_Voucher is Null)
              and a.vm_voucher_type =''SRV''
              )) Src
    on (trg.v_type = src.voucher_type and trg.v_no = src.voucher_no and trg.v_date = src.voucher_date)
    when matched then
    update set
    trg.v_chq = src.cheque_no, trg.v_bankcode = src.bank_code ,trg.v_debit=src.debit, trg.v_credit=src.credit, trg.v_narration=src.narration
    when not matched then
    insert (trg.v_type, trg.v_no, trg.v_date, trg.v_chq, trg.v_bankcode, trg.v_debit, trg.v_credit, trg.v_narration)
    values (src.voucher_type, src.voucher_no, src.voucher_date, src.cheque_no, src.bank_code, src.debit, src.credit, src.narration)      
    FORMS_DDL(V_COM);
    end;
    END;no any result.
    please guide me is this right way to do this. or kindly suggest me other ways to using merge statement in form.

    Hello,
    1.) why do you use dynamic SQL here? forms_ddl is a tricky one as it doesn't throw exceptions, so debugging is really fun. And I can't see any justification why this has to be dynamic SQL.
    2.) put the whole thing in a stored procedure and call this procedure. write once, run everywhere.
    cheers

  • Error executing a stored procedure from SSIS using the MERGE statement between databases

    Good morning,
    I'm trying to execute from SSIS a stored procedure that compares the content of two tables on different databases in the same server and updates one of them. To perform this action, I've created a stored procedure in the destination database and I'm
    comparing the data between tables with the MERGE statement. When I execute the procedure on the destination database the error that I obtain is:
    "Msg 916, Level 14, State 1, Procedure RefreshDestinationTable, Line 13
    The server principal "XXXX" is not able to access the database "XXXX" under the current security context."
    Some things to take in account:
    1. I've created a temporary table on the same destination database to check if the problem was on the MERGE statement and it works fine.
    2. I've created the procedure with the option "WITH EXECUTE AS DBO".
    I've read that it can be a problem of permissions but I don't know if I'm executing the procedure from SSIS to which user/login I should give permissions and which.
    Could you give me some tip to continue investigating how to solve the problem?
    Thank you,
    Virgilio

    Read Erland's article http://www.sommarskog.se/grantperm.html
    Best Regards,Uri Dimant SQL Server MVP,
    http://sqlblog.com/blogs/uri_dimant/
    MS SQL optimization: MS SQL Development and Optimization
    MS SQL Consulting:
    Large scale of database and data cleansing
    Remote DBA Services:
    Improves MS SQL Database Performance
    SQL Server Integration Services:
    Business Intelligence

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

  • 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

Maybe you are looking for

  • Multiple animations in one animation?

    Hello, I have 2 Flash animations, both tweened and working as intended, and now I'd like to make a third flash animation which will be composed of the other 2 animations playing after each other (with a few empty frames in between). How I do this? I

  • Inherited first gen Macbook Pro

    Hey everyone, I have a somewhat vague question. I recently swapped computers with my wife, inheriting her first generation Macbook Pro, which has surprisingly withstood the test of time. Right now I'm trying to maximize the performance so that I can

  • Drag and Drop Restore Issue

    The hard drive on my first generation MacBook Air failed, and I had it replaced by Apple. They reinstalled all of the Apple software that was on my old drive. Now I'm trying to restore using a sparsebundle that I keep on an external drive. That part

  • The Best Tool For Multiple Animated Objects

    Hi, I am expirimenting with Flash Web Sites, and I would like suggestions as to a starting point for my project, and I am assuming a Flash website is where I would start. Basically, If I were to open up a web page, I would like to see multiple animat

  • Query Logic for Collections

    Is it possible to create a collection query that will filter on the active directory computer description? We use a 3 letter code in the computer descript of each AD computer object and I need to create a query based on a particular 3-letter code.