Oracle Merge query

Hi ,
I am writing a merge query for a Java application. I have a screen and I am going to take the values in the screen and check if those values exist in the database. If they exist, then I will have to update the data, else I will have to insert the data.
The query is like
MERGE INTO XYZ USING
(SELECT BONUS_ID,CUST_NBR FROM XYZ)B ON
(B.BONUS_ID = 2027 and B.CUST_NBR='181258225')
WHEN MATCHED THEN UPDATE SET
CUST_TYPE= 'S', REV_AMT= 123, POUND_TOTAL= 123, PKG_TOTAL= 123 WHERE
CUST_NBR = '181258225'
WHEN NOT MATCHED THEN INSERT
But this query is not working. I get the "Missing Keyword"

I meant nothing else
update xyz set ... where ...;
and
insert into xyz select ... from xyz where ...;
I wrote "When I check B.Bonus_ID it refers to the BonusID from XYZ table".
Let me give you one example with SCOTT schema.
I hope it illustrates well my concern of your
statement:
SQL> select ename, empno, sal from emp;
&nbsp
ENAME                     EMPNO        SAL
SMITH                      7369        800
ALLEN                      7499       1600
WARD                       7521       1250
JONES                      7566       2975
MARTIN                     7654       1250
BLAKE                      7698       2850
CLARK                      7782       2450
SCOTT                      7788       3000
KING                       7839       5000
TURNER                     7844       1500
ADAMS                      7876       1100
JAMES                      7900        950
FORD                       7902       3000
MILLER                     7934       1300
&nbsp
14 rows selected.
&nbsp
SQL> merge into emp using (select * from emp) b
  2  on (b.ename = 'KING')
  3  when matched then update set sal = 1000
  4  when not matched then insert (emp.empno, emp.ename, emp.deptno, emp.sal
  5  values(-b.empno, b.ename, b.deptno, 0)
  6  /
&nbsp
27 rows merged.
&nbsp
SQL> select ename, empno, sal from emp;
&nbsp
ENAME                     EMPNO        SAL
SMITH                     -7369          0
ALLEN                     -7499          0
WARD                      -7521          0
JONES                     -7566          0
MARTIN                    -7654          0
BLAKE                     -7698          0
CLARK                     -7782          0
SCOTT                     -7788          0
TURNER                    -7844          0
ADAMS                     -7876          0
JAMES                     -7900          0
FORD                      -7902          0
MILLER                    -7934          0
SMITH                      7369       1000
ALLEN                      7499       1000
WARD                       7521       1000
JONES                      7566       1000
MARTIN                     7654       1000
BLAKE                      7698       1000
CLARK                      7782       1000
SCOTT                      7788       1000
KING                       7839       1000
TURNER                     7844       1000
ADAMS                      7876       1000
JAMES                      7900       1000
FORD                       7902       1000
MILLER                     7934       1000
&nbsp
27 rows selected.Rgds.

Similar Messages

  • Strange Condition Oracle Merge

    I have an Oracle Merge statement. The condition I am facing is that the statement is updating the table as well as inserting the record that its updated. I have duplicates in the table for this reason. Can someone please advice why this condition occurs? the primary key constraint of the table is disabled.

    The Merge statement is attached below. I am selecting my query from a view thats based on a table. My aim is to generate a summary at a level higher than that of the table. date_key here refers to the weekend date. ITs used instead of a week id.
    My problem is that the table has duplicate records after the merge. when i run the select part of this merge, it doesnt get me any duplicates.
    MERGE INTO WEEKLY_PGROUP_SUMMARY w
    USING (
    SELECT date_key, ccid, year_id, period_id, week_id, company, country,
    location, brand, mainbrand, pgroup,
    sales_qty, sales_cost, sales_value,
    fp_sales_qty, fp_sales_cost, fp_sales_value,
    md_sales_qty, md_sales_cost, md_sales_value,
    sreturns_qty, sreturns_cost, sreturns_value,
    grn_qty, grn_cost, grn_value,
    tfrin_qty, tfrin_cost, tfrin_value,
    tfrout_qty, tfrout_cost, tfrout_value,
    intake_qty, intake_cost, intake_value,
    preturns_qty, preturns_cost, preturns_value,
    adjm_qty, adjm_cost, adjm_value,
    adjw_qty, adjw_cost, adjw_value,
    adjc_qty, adjc_cost, adjc_value,
    adjt_qty, adjt_cost, adjt_value,
    adjv_qty, adjv_cost, adjv_value,
    stockob_qty, stockob_cost, stockob_value,
    fp_stockob_qty, fp_stockob_cost, fp_stockob_value,
    md_stockob_qty, md_stockob_cost, md_stockob_value,
    tm_stockob_qty, tm_stockob_cost, tm_stockob_value,
    stockcl_qty, stockcl_cost, stockcl_value,
    fp_stockcl_qty, fp_stockcl_cost, fp_stockcl_value,
    md_stockcl_qty, md_stockcl_cost, md_stockcl_value,
    se_stockcl_qty, tm_stockcl_cost, tm_stockcl_value,
    tm_stockcl_qty, se_stockcl_cost, se_stockcl_value,
    co_stockcl_qty, co_stockcl_cost, co_stockcl_value,
    currency, exrate1, exrate2, exrate3, exrate4, exrate5
    FROM generate_pgroup_summary_v ) v
    -- On condition includes all fields that are indexed
    ON (v.date_key = w.date_key AND v.ccid = w.ccid AND v.brand = w.brand
    AND v.pgroup = w.pgroup)
    WHEN MATCHED THEN
    UPDATE
    SET w.currency = v.currency,
    w.exrate1 = v.exrate1,
    w.exrate2 = v.exrate2,
    w.exrate3 = v.exrate3,
    w.exrate4 = v.exrate4,
    w.exrate5 = v.exrate5,
    w.sales_qty = v.sales_qty,
    w.sales_cost = v.sales_cost,
    w.sales_value = v.sales_value,
    w.fp_sales_qty = v.fp_sales_qty,
    w.fp_sales_cost = v.fp_sales_cost,
    w.fp_sales_value = v.fp_sales_value,
    w.md_sales_qty = v.md_sales_qty,
    w.md_sales_cost = v.md_sales_cost,
    w.md_sales_value = v.md_sales_value,
    w.sreturns_qty = v.sreturns_qty,
    w.sreturns_cost = v.sreturns_cost,
    w.sreturns_value = v.sreturns_value,
    w.grn_qty = v.grn_qty,
    w.grn_cost = v.grn_cost,
    w.grn_value = v.grn_value,
    w.tfrin_qty = v.tfrin_qty,
    w.tfrin_cost = v.tfrin_cost,
    w.tfrin_value = v.tfrin_value,
    w.tfrout_qty = v.tfrout_qty,
    w.tfrout_cost = v.tfrout_cost,
    w.tfrout_value = v.tfrout_value,
    w.intake_qty = v.intake_qty,
    w.intake_cost = v.intake_cost,
    w.intake_value = v.intake_value,
    w.preturns_qty = v.preturns_qty,
    w.preturns_cost = v.preturns_cost,
    w.preturns_value = v.preturns_value,
    w.adjm_qty = v.adjm_qty,
    w.adjm_cost = v.adjm_cost,
    w.adjm_value = v.adjm_value,
    w.adjw_qty = v.adjw_qty,
    w.adjw_cost = v.adjw_cost,
    w.adjw_value = v.adjw_value,
    w.adjc_qty = v.adjc_qty,
    w.adjc_cost = v.adjc_cost,
    w.adjc_value = v.adjc_value,
    w.adjt_qty = v.adjt_qty,
    w.adjt_cost = v.adjt_cost,
    w.adjt_value = v.adjt_value,
    w.adjv_qty = v.adjv_qty,
    w.adjv_cost = v.adjv_cost,
    w.adjv_value = v.adjv_value,
    w.stockob_qty = v.stockob_qty,
    w.stockob_cost = v.stockob_cost,
    w.stockob_value = v.stockob_value,
    w.fp_stockob_qty = v.fp_stockob_qty,
    w.fp_stockob_cost = v.fp_stockob_cost,
    w.fp_stockob_value = v.fp_stockob_value,
    w.md_stockob_qty = v.md_stockob_qty,
    w.md_stockob_cost = v.md_stockob_cost,
    w.md_stockob_value = v.md_stockob_value,
    w.tm_stockob_qty = v.tm_stockob_qty,
    w.tm_stockob_cost = v.tm_stockob_cost,
    w.tm_stockob_value = v.tm_stockob_value,
    w.stockcl_qty = v.stockcl_qty,
    w.stockcl_cost = v.stockcl_cost,
    w.stockcl_value = v.stockcl_value,
    w.fp_stockcl_qty = v.fp_stockcl_qty,
    w.fp_stockcl_cost = v.fp_stockcl_cost,
    w.fp_stockcl_value = v.fp_stockcl_value,
    w.md_stockcl_qty = v.md_stockcl_qty,
    w.md_stockcl_cost = v.md_stockcl_cost,
    w.md_stockcl_value = v.md_stockcl_value,
    w.se_stockcl_qty = v.se_stockcl_qty,
    w.se_stockcl_cost = v.se_stockcl_cost,
    w.se_stockcl_value = v.se_stockcl_value,
    w.tm_stockcl_qty = v.tm_stockcl_qty,
    w.tm_stockcl_cost = v.tm_stockcl_cost,
    w.tm_stockcl_value = v.tm_stockcl_value,
    w.co_stockcl_qty = v.co_stockcl_qty,
    w.co_stockcl_cost = v.co_stockcl_cost,
    w.co_stockcl_value = v.co_stockcl_value,
    w.modifiedon=stime
    WHEN NOT MATCHED THEN
    INSERT (date_key, ccid, year_id, period_id, week_id,
    company, country,location, brand, mainbrand,
    pgroup,
    sales_qty, sales_cost, sales_value,
    fp_sales_qty, fp_sales_cost, fp_sales_value,
    md_sales_qty, md_sales_cost, md_sales_value,
    sreturns_qty, sreturns_cost, sreturns_value,
    grn_qty, grn_cost, grn_value,
    tfrin_qty, tfrin_cost, tfrin_value,
    tfrout_qty, tfrout_cost, tfrout_value,
    intake_qty, intake_cost, intake_value,
    preturns_qty, preturns_cost, preturns_value,
    adjm_qty, adjm_cost, adjm_value,
    adjw_qty, adjw_cost, adjw_value,
    adjc_qty, adjc_cost, adjc_value,
    adjt_qty, adjt_cost, adjt_value,
    adjv_qty, adjv_cost, adjv_value,
    stockob_qty, stockob_cost, stockob_value,
    fp_stockob_qty, fp_stockob_cost, fp_stockob_value,
    md_stockob_qty, md_stockob_cost, md_stockob_value,
    tm_stockob_qty, tm_stockob_cost, tm_stockob_value,
    stockcl_qty, stockcl_cost, stockcl_value,
    fp_stockcl_qty, fp_stockcl_cost, fp_stockcl_value,
    md_stockcl_qty, md_stockcl_cost, md_stockcl_value,
    se_stockcl_qty, tm_stockcl_cost, tm_stockcl_value,
    tm_stockcl_qty, se_stockcl_cost, se_stockcl_value,
    co_stockcl_qty, co_stockcl_cost, co_stockcl_value,
    currency, exrate1, exrate2, exrate3, exrate4, exrate5,
    modifiedon)
    values
    (v.date_key, v.ccid, v.year_id, v.period_id, v.week_id, v.company, v.country,
    v.location, v.brand, v.mainbrand, v.pgroup,
    v.sales_qty, v.sales_cost, v.sales_value,
    v.fp_sales_qty, v.fp_sales_cost, v.fp_sales_value,
    v.md_sales_qty, v.md_sales_cost, v.md_sales_value,
    v.sreturns_qty, v.sreturns_cost, v.sreturns_value,
    v.grn_qty, v.grn_cost, v.grn_value,
    v.tfrin_qty, v.tfrin_cost, v.tfrin_value,
    v.tfrout_qty, v.tfrout_cost, v.tfrout_value,
    v.intake_qty, v.intake_cost, v.intake_value,
    v.preturns_qty, v.preturns_cost, v.preturns_value,
    v.adjm_qty, v.adjm_cost, v.adjm_value,
    v.adjw_qty, v.adjw_cost, v.adjw_value,
    v.adjc_qty, v.adjc_cost, v.adjc_value,
    v.adjt_qty, v.adjt_cost, v.adjt_value,
    v.adjv_qty, v.adjv_cost, v.adjv_value,
    v.stockob_qty, v.stockob_cost, v.stockob_value,
    v.fp_stockob_qty, v.fp_stockob_cost, v.fp_stockob_value,
    v.md_stockob_qty, v.md_stockob_cost, v.md_stockob_value,
    v.tm_stockob_qty, v.tm_stockob_cost, v.tm_stockob_value,
    v.stockcl_qty, v.stockcl_cost, v.stockcl_value,
    v.fp_stockcl_qty, v.fp_stockcl_cost, v.fp_stockcl_value,
    v.md_stockcl_qty, v.md_stockcl_cost, v.md_stockcl_value,
    v.se_stockcl_qty, v.tm_stockcl_cost, v.tm_stockcl_value,
    v.tm_stockcl_qty, v.se_stockcl_cost, v.se_stockcl_value,
    v.co_stockcl_qty, v.co_stockcl_cost, v.co_stockcl_value,
    v.currency, v.exrate1, v.exrate2, v.exrate3, v.exrate4, v.exrate5,
    stime);

  • Merge query error in Where clause

    Following error is coming when i execute the merge query. Anything wrong with this? I am using Oracle 9.2.0.1.
    Query:
    MERGE
         INTO incompletekalls ic
         USING live_small ls
         ON ((ls.callid = ic.callid) AND
         (ls.sdate = ic.sdate) AND
         (ls.stime = ic.stime))
    WHEN MATCHED THEN
         UPDATE
         SET     ic.adate = ls.adate,
              ic.atime = ls.atime,
              ic.edate = ls.edate,
              ic.etime = ls.etime
         WHERE
              ls.sdate = '16-Apr-09' AND ls.stime >= '09:00:00' AND ls.stime <= '11:00:00' AND ((ls.adate IS NULL) OR
              (ls.edate IS NULL))
    WHEN NOT MATCHED THEN
         INSERT (ic.callid,ic.cg,ic.cd,ic.re,ic.opc,ic.dpc,ic.sdate,ic.stime,ic.adate,ic.atime,ic.edate,ic.etime)
         VALUES (ls.callid,ls.cg,ls.cd,ls.re,ls.opc,ls.dpc,ls.sdate,ls.stime,ls.adate,ls.atime,ls.edate,ls.etime)
         WHERE ls.sdate >= '16-Apr-09' AND ls.stime >= '09:00:00' AND ls.stime <= '11:00:00'
    Error:
    SQL> /
    WHERE
    ERROR at line 13:
    ORA-00905: missing keyword

    Hi,
    From looking at the documented examples
    http://www.oracle.com/pls/db92/db92.drilldown?levelnum=2&toplevel=a96540&method=FULL&chapters=0&book=&wildcards=1&preference=&expand_all=&verb=&word=MERGE#a96540
    and on http://asktom.oracle.com/pls/asktom/f?p=100:11:0::::P11_QUESTION_ID:5318183934935
    I think that you cannot use the WHERE in your MERGE like that on 9i...
    Something else I want to warn you for:
    It's a bad idea to store your date and time separated as strings! You'll run into troubles sooner or later, for 100%...
    Use a single DATE column instead, in which you store both the date and time components..

  • Need help optimizing a merge query

    Hi all, I hope someone can give me some assistance with this. I don't have a lot of experience with Oracle, so any help would be greatly appreciated. I have a MERGE query that I need to optimize as much as possible. I will give as much information as I can in this post.
    Here is the actual query:
          MERGE INTO quick_scene_lookup qsl
          USING (
            SELECT scene.*,
              CASE
                WHEN scene.data_category LIKE 'NOM%'
                  THEN 'NOM'
                WHEN scene.data_category LIKE 'ENG%'
                  THEN 'ENG'
                WHEN scene.data_category LIKE 'VAL%'
                  THEN 'VAL'
                ELSE scene.data_category
              END scn_data_category,
              CASE
                WHEN scene.data_category_original LIKE 'NOM%'
                  THEN 'NOM'
                WHEN scene.data_category_original LIKE 'ENG%'
                  THEN 'ENG'
                WHEN scene.data_category_original LIKE 'VAL%'
                  THEN 'VAL'
                ELSE scene.data_category_original
              END data_category_orig,
              CASE
                WHEN scene.full_partial_scene LIKE 'F%'
                  THEN 'F'
                WHEN scene.full_partial_scene LIKE 'P%'
                  THEN 'P'
                ELSE scene.full_partial_scene
              END scn_full_partial_scene,
              CASE
                WHEN scene.date_entered_lam IS NULL
                    OR scene.deleted = 1
                  THEN 0
                ELSE 1
              END in_lam,
              CASE
                WHEN scene.in_uis LIKE 'Y%'
                  THEN 1
                ELSE 0
              END scn_in_uis,
              CASE
                WHEN scene.data_category LIKE 'NOM%'
                    AND scene.full_partial_scene LIKE 'F%'
                  THEN 1
                ELSE 0
              END monitor,
              CASE
                WHEN scene.date_updated_lam IS NOT NULL
                    AND scene.satellite_sensor_key = 8 -- L7 ETM
                  THEN
                    CASE
                      WHEN intv.match_in_tolerance = 'Y'
                          OR intv.match_in_tolerance = 'N'
                        THEN 0
                      ELSE 1
                    END
                 ELSE 0
              END lam_orphan,
              sat.satellite,
              sat.sensor_id,
              station.station_id,
              intv.match_in_tolerance,
              wrs.wrs_path,
              wrs.wrs_row,
              TO_DATE(SUBSTR(scene.scene_start_time, 0, 17),
                  'YYYY:DDD:HH24:MI:SS') scn_scene_start_time,
              CASE
                WHEN qsl.date_downlinked IS NOT NULL
                    AND scene.date_standing_request IS NOT NULL
                  THEN (qsl.date_downlinked - scene.date_standing_request) * 1440
                ELSE NULL
              END dd_downlinked_marketable
            FROM all_scenes scene
            INNER JOIN lu_satellite sat
              ON (scene.satellite_sensor_key = sat.satellite_sensor_key)
            INNER JOIN ground_stations station
              ON (scene.station_key = station.station_key)
            INNER JOIN all_intervals intv
              ON (scene.landsat_interval_id = intv.landsat_interval_id)
            INNER JOIN worldwide_reference_system wrs
              ON (scene.wrs_key = wrs.wrs_key)
            LEFT OUTER JOIN quick_scene_lookup qsl
              ON (scene.landsat_scene_id = qsl.landsat_scene_id)
            WHERE (scene.job_sequence_key IN (
              SELECT job_sequence_key FROM jobs_subscript_execution_fact
              WHERE job_key = 109)
            OR qsl.landsat_scene_id IS NULL)
            AND scene.scene_version = (
              SELECT MAX(scene_version) FROM all_scenes
              WHERE SUBSTR(landsat_scene_id, 1, 19) =
                SUBSTR(scene.landsat_scene_id, 1, 19))) scenes
          ON (qsl.landsat_scene_id = scenes.landsat_scene_id
            OR (qsl.satellite = scenes.satellite
              AND qsl.station_id = scenes.station_id
              AND qsl.wrs_path = scenes.wrs_path
              AND qsl.wrs_row = scenes.wrs_row
              AND TRUNC(qsl.date_acquired) = TRUNC(scenes.date_acquired)
              AND SUBSTR(qsl.sensor_id, 1, 3) = SUBSTR(scenes.sensor_id, 1, 3)))
          WHEN MATCHED THEN
          UPDATE SET
            data_category = scenes.scn_data_category,
            data_category_original = scenes.data_category_orig,
            date_acquired = scenes.date_acquired,
            date_entered = scenes.date_entered,
            date_standing_request = scenes.date_standing_request,
            date_updated = scenes.date_updated,
            dd_downlinked_marketable = scenes.dd_downlinked_marketable,
            full_partial_scene = scenes.scn_full_partial_scene,
            in_lam = scenes.in_lam,
            in_uis = scenes.scn_in_uis,
            lam_orphan = scenes.lam_orphan,
            monitor = scenes.monitor,
            satellite = scenes.satellite,
            scene_start_time_date = scenes.scn_scene_start_time,
            sensor_id = scenes.sensor_id,
            station_id = scenes.station_id,
            wrs_path = scenes.wrs_path,
            wrs_row = scenes.wrs_row,
            cloud_cover = scenes.cloud_cover
          WHEN NOT MATCHED THEN INSERT(
            qsl_scene_id,
            data_category,
            data_category_original,
            date_acquired,
            date_entered,
            date_standing_request,
            date_updated,
            full_partial_scene,
            in_lam,
            in_moc,
            in_uis,
            lam_orphan,
            landsat_interval_id,
            landsat_scene_id,
            monitor,
            satellite,
            scene_start_time_date,
            sensor_id,
            station_id,
            wrs_path,
            wrs_row,
            cloud_cover)
          VALUES(
            seq_qsl_scene_id.nextval,
            scenes.scn_data_category,
            scenes.data_category_orig,
            scenes.date_acquired,
            scenes.date_entered,
            scenes.date_standing_request,
            scenes.date_updated,
            scenes.scn_full_partial_scene,
            scenes.in_lam,
            0,     -- in_moc will always be 0 for archive inserts
            scenes.scn_in_uis,
            scenes.lam_orphan,
            scenes.landsat_interval_id,
            scenes.landsat_scene_id,
            scenes.monitor,
            scenes.satellite,
            scenes.scn_scene_start_time,
            scenes.sensor_id,
            scenes.station_id,
            scenes.wrs_path,
            scenes.wrs_row,
            scenes.cloud_cover)
        LOG ERRORS INTO ingest_errors('Intervals error')
          REJECT LIMIT 500;All of the columns used in the joins have indexes. Also, all columns referenced in the WHERE clause also have indexes. I have function based indexes on the two columns that are using a function.
    The cost from the explain plan is at 14 million, and this query takes far too long to run. I can post the explain plan if anybody wants it. We are running Oracle 10.2g, and are a data warehouse. Any help I can get on this would be greatly appreciated, I and my dba's are unable to come up with any more ideas. Thanks in advance.

    Well, just in case this might help someone else out, I was able to resolve my issue with the code. It turns out that in the secondary condition of the ON clause for the merge, I had columns that were also being updated. By removing the those columns from the UPDATE clause. It dropped my cost down to 456,000. I was further able to reduce the cost of the query by removing the primary conditional completely. I am a C++ programmer and was counting on a short-circuit OR to speed up the process. Anyway, my cost is now down to 215,000, and all is good here.
    Thanks.

  • Oracle MERGE in to a single table error.

    Experts, please find any errors in this merge query as it throws following exception when trying to execute,
    MERGE INTO md.PER_USER PU
    USING (
    SELECT
    +'aaa.bbb.ccc' AS NAME,+
    +'222' AS VALUE,+
    +( SELECT U_ID+
    FROM  md.USER U
    WHERE  upper(U.NAME) = upper('sds')) AS U_ID
    FROM dual
    +) val ON (+
    PU.NAME=val.NAME
    and PU.U_ID=val.U_ID
    +)+
    WHEN MATCHED THEN
    update set PU.VALUE = val.value
    WHEN NOT MATCHED THEN
    INSERT (PU.ID, PU.NAME, PU.VALUE,PU.U_ID) VALUES (SELECT sys_guid(), val.NAME, val.VALUE,val.U_ID);
    Following exception throws :
    nested exception is java.sql.SQLSyntaxErrorException: ORA-00936: missing expression'; cause: 'org.springframework.jdbc.BadSqlGrammarException';
    Iam using oracle 11g.

    INSERT (PU.ID, PU.NAME, PU.VALUE,PU.U_ID) VALUES (SELECT sys_guid(), val.NAME, val.VALUE,val.U_ID);leave away the SELECT before sys_guid():
    INSERT (PU.ID, PU.NAME, PU.VALUE,PU.U_ID) VALUES (sys_guid(), val.NAME, val.VALUE,val.U_ID);

  • Implementing Auto Correct Load as Oracle Merge

    Data Services 3.0 documentation reads that Auto Correct Load option for Oracle target will be implemented as a Merge statement, if both the source and the target reside in the same datastore.
    I have set this up as per documentation, however the Optimized SQL still shows a pl/sql stored procedure logic, NOT the Merge Statement.
    My questions are:
    1. Has anybody successfully implemented Oracle Merge?
    2. If answer to (1) is yes, then is there a way to control update and insert elements of the Merge statement? I would like to update the rec_created_timestamp of the target table only on Insert, and update the rec_updated_timestamp on update.
    Thank you.

    having both source and target on the same database or source table accesible from target table throguh Database link is not the only condition for DS Optimizer to use Oracle MERGE command to do auto correct load
    check the following
    Auto Correct load and Allow Merge option is set to yes for target table
    its possible to push down the complete read and load operation to DB, (you are not using function or mapping or join etc that are not supported by Oracle)
    You have Primary Keys defined correctly, this is required to avoid situation where you may not end up inserting and updating the same record (MERGE will fail with Ora error )
    the Identification of INSERT and UPDATE will depend on your key column, you can modify the PK for target table either modfiying the table column properties by opening the schema from Datastore or if you want this only for a particular DF then add a Query transfrom before loader and set the key columns in output schema and set the loader option Use Input Key to yes
    Using User Defined key is safe as long as you make sure that the source data will be unique for that combination else MERGE will fail

  • Executing a merge query for a collection

    Hello All,
    I am trying to use a merge query to find common and uncommon ids between a table and a list I pass to my pl-sql proc. I am not sure if I am doing the right thing, please guide me...
    Here is my code...
    Procedure process_content(i_eidlist IN ocs_eid_list_t, i_id IN number, o_new_email_list OUT ocs_eid_list_t) AS
    lv_last_processed_row_id number;
    lv_common_email_list ocs_eid_list_t;
    lv_internet_id varchar2;
    Begin
    lv_last_processed_row_id := 0;
    MERGE INTO table c
    USING TABLE(i_eidlist)a
    ON (c.eid in a)
    --WHEN MATCHED THEN UPDATE SET c.row_id = job_no_seq.NEXTVAL,c.copy_count=1 returning row_id bulk collect into lv_row_id_list;
    WHEN MATCHED THEN SELECT c.eid bulk collect into lv_common_email_list returning row_id bulk collect into lv_row_id_list
    WHEN NOT MATCHED THEN SELECT c.eid bulk collect into o_new_email_list;
    I am assuming that the merge query is going to iterate over the i_eidlist, and find me the common and uncommon elements. However, I get an error saying the sql block is ignored.
    Thanks
    Abhishek
    글 수정: A.J.

    I do not think it is possible in one pass. The best I could come up with:
    DECLARE
        COMMON_LIST NAME_LIST;
        UNCOMMON_LIST NAME_LIST;
        EMPLOYEE_LIST NAME_LIST;
        CHECK_LIST NAME_LIST := NAME_LIST('KING','QUEEN');
    BEGIN
        SELECT  ENAME
          BULK COLLECT INTO EMPLOYEE_LIST
          FROM  EMP;
        COMMON_LIST := EMPLOYEE_LIST MULTISET INTERSECT CHECK_LIST;
        UNCOMMON_LIST := EMPLOYEE_LIST MULTISET EXCEPT CHECK_LIST;
    DBMS_OUTPUT.PUT_LINE('-- COMMON_LIST --');
    FOR i IN 1..COMMON_LIST.COUNT LOOP
      DBMS_OUTPUT.PUT_LINE(COMMON_LIST(i));
    END LOOP;
    DBMS_OUTPUT.PUT_LINE('-- UNCOMMON_LIST --');
    FOR i IN 1..UNCOMMON_LIST.COUNT LOOP
      DBMS_OUTPUT.PUT_LINE(UNCOMMON_LIST(i));
    END LOOP;
    END;
    /Run results showing contents:
    SQL> DECLARE
      2      COMMON_LIST NAME_LIST;
      3      UNCOMMON_LIST NAME_LIST;
      4      EMPLOYEE_LIST NAME_LIST;
      5      CHECK_LIST NAME_LIST := NAME_LIST('KING','QUEEN');
      6  BEGIN
      7      SELECT  ENAME
      8        BULK COLLECT INTO EMPLOYEE_LIST
      9        FROM  EMP;
    10      COMMON_LIST := EMPLOYEE_LIST MULTISET INTERSECT CHECK_LIST;
    11      UNCOMMON_LIST := EMPLOYEE_LIST MULTISET EXCEPT CHECK_LIST;
    12  DBMS_OUTPUT.PUT_LINE('-- COMMON_LIST --');
    13  FOR i IN 1..COMMON_LIST.COUNT LOOP
    14    DBMS_OUTPUT.PUT_LINE(COMMON_LIST(i));
    15  END LOOP;
    16  DBMS_OUTPUT.PUT_LINE('-- UNCOMMON_LIST --');
    17  FOR i IN 1..UNCOMMON_LIST.COUNT LOOP
    18    DBMS_OUTPUT.PUT_LINE(UNCOMMON_LIST(i));
    19  END LOOP;
    20  END;
    21  /
    -- COMMON_LIST --
    KING
    -- UNCOMMON_LIST --
    SMITH
    ALLEN
    WARD
    JONES
    MARTIN
    BLAKE
    CLARK
    SCOTT
    TURNER
    ADAMS
    JAMES
    FORD
    MILLER
    PL/SQL procedure successfully completed.
    SQL> SY.

  • Error in merge query of the Proc.

    Hi all,
    Below merge query working fine, if I execite independently. I am getting error as "ORA-00900: invalid SQL statement" when i paste this code inside the procedure. However, if I comment the lines written in bold, proc is working fine. Not sure why the comparison not happening even though code and data is correct. If i use like intead of IN then it is working fine.
    Can you please suggest on this?
    MERGE INTO ENTRYPOINTASSETS
    USING
    (SELECT
    LAST_DAY(TRUNC(to_timestamp(oa.reqdate, 'yyyymmddhh24:mi:ss.ff4'))) as activity_month,
    oa.acctnum as acctnum,
    l.lkpvalue as assettype,
    LOWER(trim(oa.disseminationmthd)) as deliverymthd,
    epa.assetid as assetid,
    epa.assetname as assetname,
    count(1) as entrypointcount
    FROM action oa, asset epa, lookupdata l
    WHERE
    oa.assetkey IS NOT NULL
    AND oa.acctnum is not null
    AND trim(oa.assettype) IN ('NL','WS','AL')
    AND l.lkpid = epa.assettypeid
    AND UPPER(trim(oa.disseminationmthd)) IN ('ABC','BCD', 'PODCAST', 'EMAIL','ED', 'WID')
    AND epa.assetkey = oa.assetkey
    AND epa.assetid <> 0
    GROUP BY
    LAST_DAY(TRUNC(to_timestamp(oa.reqdate, 'yyyymmddhh24:mi:ss.ff4'))),
    oa.acctnum,
    l.lkpvalue,
    LOWER(trim(oa.disseminationmthd)),
    epa.assetid,
    epa.assetname
    ) cvd1
    ON
    (ENTRYPOINTASSETS.activity_month = cvd1.activity_month
    AND ENTRYPOINTASSETS.acctnum = cvd1.acctnum
    AND ENTRYPOINTASSETS.assettype = cvd1.assettype
    AND UPPER(ENTRYPOINTASSETS.deliverymthd) = UPPER(cvd1.deliverymthd)
    AND ENTRYPOINTASSETS.assetid = cvd1.assetid)
    WHEN NOT MATCHED THEN
    INSERT (activity_month, acctnum, assettype, deliverymthd, assetid, assetname, entrypointcount)
    VALUES (cvd1.activity_month, cvd1.acctnum, cvd1.assettype, cvd1.deliverymthd, cvd1.assetid, cvd1.assetname, cvd1.entrypointcount)
    WHEN MATCHED THEN
    UPDATE
    SET ENTRYPOINTASSETS.assetname = cvd1.assetname;
    Edited by: Nagaraja Akkivalli on Aug 9, 2011 6:07 PM

    Tried it. No luck. Facing the same problem.
    MERGE INTO SUMMARYTABLE
    USING
    (SELECT
    LAST_DAY(TRUNC(to_timestamp(oa.reqdate, 'yyyymmddhh24:mi:ss.ff4'))) as activity_month,
            oa.acctnum as acctnum,
            l.lkpvalue as assettype,
            LOWER(TRIM(oa.disseminationmthd)) as deliverymthd,
            epa.assetid as assetid,
            epa.assetname as assetname,
            count(1) as entrypointcount
       FROM ods_action oa, ods_asset epa, ods_lookupdata l
      WHERE
         (lv_summm_type_indicator  = c_summaryType_fullLoad
         AND  ( get_date_timestamp(oa.reqdate) BETWEEN :sum_startdate AND :sum_enddate
         AND   oa.uploaddatetime BETWEEN :partitioned_start_date AND :partitioned_end_date
         OR (lv_summm_type_indicator = c_summaryType_incrementLoad
                    AND oa.uploaddatetime BETWEEN :sum_startdate AND :sum_enddate )
        AND oa.assetkey IS NOT NULL
        AND oa.acctnum is not null
        AND UPPER(TRIM(oa.assettype)) IN ('NL','WS','AL')
        AND l.lkpid = epa.assettypeid
        AND UPPER(TRIM(oa.disseminationmthd)) IN ('RSS','PCAST', 'PODCAST', 'EMAIL','ED', 'WID')
        AND epa.assetkey = oa.assetkey
        AND epa.assetid <> 0
      GROUP BY
      LAST_DAY(TRUNC(to_timestamp(oa.reqdate, 'yyyymmddhh24:mi:ss.ff4'))),
               oa.acctnum,
               l.lkpvalue,
               LOWER(TRIM(oa.disseminationmthd)),
               epa.assetid,
               epa.assetname
           ) cvd1
    ON
       (SUMMARYTABLE.activity_month = cvd1.activity_month
        AND SUMMARYTABLE.acctnum = cvd1.acctnum
        AND SUMMARYTABLE.assettype = cvd1.assettype
        AND UPPER(TRIM(SUMMARYTABLE.deliverymthd)) = UPPER(TRIM(cvd1.deliverymthd))
        AND SUMMARYTABLE.assetid = cvd1.assetid)
    WHEN NOT MATCHED THEN
    INSERT (activity_month, acctnum, assettype, deliverymthd, assetid, assetname, entrypointcount)
    VALUES (cvd1.activity_month, cvd1.acctnum, cvd1.assettype, cvd1.deliverymthd, cvd1.assetid, cvd1.assetname, cvd1.entrypointcount)
    WHEN MATCHED THEN
    UPDATE
    SET SUMMARYTABLE.assetname = cvd1.assetname,
        SUMMARYTABLE.entrypointcount =
         CASE WHEN NVL(lv_summm_type_indicator,c_summaryType_incrementLoad) = c_summaryType_fullLoad THEN cvd1.entrypointcount
         ELSE SUMMARYTABLE.entrypointcount + cvd1.entrypointcount END;If I comment any one of the below piece of code present in merge then merge is working fine. If I retain both code then getting error.
    lv_summm_type_indicator is a variable caclualted @ run time to check type of summarization and c_summaryType_incrementLoad is a constant value stored @ the top of the procedure. PLease let me now where I am going wrong.
         (lv_summm_type_indicator  = c_summaryType_fullLoad
         AND  ( get_date_timestamp(oa.reqdate) BETWEEN :sum_startdate AND :sum_enddate
         AND   oa.uploaddatetime BETWEEN :partitioned_start_date AND :partitioned_end_date
         ))OR
    OR (lv_summm_type_indicator = c_summaryType_incrementLoad
                    AND oa.uploaddatetime BETWEEN :sum_startdate AND :sum_enddate )Edited by: Nagaraja Akkivalli on Aug 24, 2011 5:13 PM
    Edited by: Nagaraja Akkivalli on Aug 24, 2011 5:16 PM

  • Oracle Text query: Escaping characters and specifying progression sequences

    How can I combine the escaping of a search string and the specification of progression sequences within an oracle text query
    so that in all cases the correct results are delivered (see example below)?
    The scenario in which to use this is the following:
    + Database: Oracle Database 10g Enterprise Edition Release 10.2.0.2.0
    + Requirement: Hitlist of results ordered by score whereby the different part within
    the result list are specified using progression sequences within oracle text query
    Example:
    create table service_provider (
    id number,
    name_c varchar(100),
    uri_c varchar(255)
    insert into service_provider values (1,'ABB Company Mgmt','http://www.abb-company-mgmt.de');
    insert into service_provider values (2,'Dr. Abbas Ming','http://www.dr-abbas-ming.de');
    insert into service_provider values (3,'SABBATA United','http://www.sabbata-united.de');
    insert into service_provider values (4,'ABB','http://www.abb.de');
    insert into service_provider values (5,'AND Company Mgmt','http://www.and-company-mgmt.de');
    insert into service_provider values (6,'Dr. Andas Ming','http://www.dr-andas-ming.de');
    insert into service_provider values (7,'SANDATA United','http://www.sandata-united.de');
    insert into service_provider values (8,'AND','http://www.and.de');
    Query 1: works correctly in this case
    select * from (
    select /*+ FIRST_ROWS */ score(1), this_.*
    from service_provider this_
    where
    CONTAINS ( this_.NAME_C , '<QUERY><textquery grammar="CONTEXT">' ||
    '<progression>' ||
    '<seq>abb</seq>' ||
    '<seq>abb%</seq>' ||
    '<seq>%abb%</seq>' ||
    '<seq>fuzzy(abb,1,100,WEIGHT)</seq>' ||
    '</progression></textquery></QUERY>', 1 ) > 0
    order by score(1) desc, this_.NAME_C
    ) where rownum < 21
    delivers
    76     4     ABB     http://www.abb.de
    76     1     ABB Company Mgmt     http://www.abb-company-mgmt.de
    51     2     Dr. Abbas Ming     http://www.dr-abbas-ming.de
    26     3     SABBATA United     http://www.sabbata-united.de
    Query 2: procudes error
    select * from (
    select /*+ FIRST_ROWS */ score(1), this_.*
    from service_provider this_
    where
    CONTAINS ( this_.NAME_C , '<QUERY><textquery grammar="CONTEXT">' ||
    '<progression>' ||
    '<seq>and</seq>' ||
    '<seq>and%</seq>' ||
    '<seq>%and%</seq>' ||
    '<seq>fuzzy(and,1,100,WEIGHT)</seq>' ||
    '</progression></textquery></QUERY>', 1 ) > 0
    order by score(1) desc, this_.NAME_C
    ) where rownum < 21
    produces ORA-29902, ORA-20000, DRG-50901 because AND is a reserved word in oracle text
    So we need escaping ...
    Query 3: does not work correctly
    select * from (
    select /*+ FIRST_ROWS */ score(1), this_.*
    from service_provider this_
    where
    CONTAINS ( this_.NAME_C , '<QUERY><textquery grammar="CONTEXT">' ||
    '<progression>' ||
    '<seq>{abb}</seq>' ||
    '<seq>{abb%}</seq>' ||
    '<seq>{%abb%}</seq>' ||
    '<seq>fuzzy({abb},1,100,WEIGHT)</seq>' ||
    '</progression></textquery></QUERY>', 1 ) > 0
    order by score(1) desc, this_.NAME_C
    ) where rownum < 21
    delivers
    76     4     ABB     http://www.abb.de
    76     1     ABB Company Mgmt     http://www.abb-company-mgmt.de
    Query 4: does not produce an error, but also does not work correctly
    select * from (
    select /*+ FIRST_ROWS */ score(1), this_.*
    from service_provider this_
    where
    CONTAINS ( this_.NAME_C , '<QUERY><textquery grammar="CONTEXT">' ||
    '<progression>' ||
    '<seq>{and}</seq>' ||
    '<seq>{and%}</seq>' ||
    '<seq>{%and%}</seq>' ||
    '<seq>fuzzy({and},1,100,WEIGHT)</seq>' ||
    '</progression></textquery></QUERY>', 1 ) > 0
    order by score(1) desc, this_.NAME_C
    ) where rownum < 21
    delivers
    76     8     AND     http://www.and.de
    76     5     AND Company Mgmt     http://www.and-company-mgmt.de

    Anywhere that you just use the word by itself, enclose it in {}, but anywhere that you add % on either side or both don't enclose it in {}. Please see the demonstration below.
    SCOTT@10gXE> SELECT * FROM v$version
      2  /
    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
    SCOTT@10gXE> create table service_provider
      2    (id     number,
      3       name_c     varchar(100),
      4       uri_c     varchar(255))
      5  /
    Table created.
    SCOTT@10gXE> insert all
      2  into service_provider values (1,'ABB Company Mgmt','http://www.abb-company-mgmt.de')
      3  into service_provider values (2,'Dr. Abbas Ming','http://www.dr-abbas-ming.de')
      4  into service_provider values (3,'SABBATA United','http://www.sabbata-united.de')
      5  into service_provider values (4,'ABB','http://www.abb.de')
      6  into service_provider values (5,'AND Company Mgmt','http://www.and-company-mgmt.de')
      7  into service_provider values (6,'Dr. Andas Ming','http://www.dr-andas-ming.de')
      8  into service_provider values (7,'SANDATA United','http://www.sandata-united.de')
      9  into service_provider values (8,'AND','http://www.and.de')
    10  into service_provider values (9,'EBB','fuzzy test')
    11  into service_provider values (10,'OND','fuzzy test')
    12  select * from dual
    13  /
    10 rows created.
    SCOTT@10gXE> CREATE INDEX your_index
      2  ON service_provider (name_c)
      3  INDEXTYPE IS CTXSYS.CONTEXT
      4  PARAMETERS ('STOPLIST CTXSYS.EMPTY_STOPLIST')
      5  /
    Index created.
    SCOTT@10gXE> VARIABLE search_string VARCHAR2 (100)
    SCOTT@10gXE> EXEC :search_string := 'abb'
    PL/SQL procedure successfully completed.
    SCOTT@10gXE> COLUMN name_c FORMAT A20 WORD_WRAPPED
    SCOTT@10gXE> COLUMN uri_c  FORMAT A40
    SCOTT@10gXE> select *
      2  from   (select /*+ FIRST_ROWS */ score(1), this_.*
      3            from   service_provider this_
      4            where  CONTAINS
      5                  (this_.NAME_C ,
      6                   '<QUERY>
      7                   <textquery grammar="CONTEXT">
      8                     <progression>
      9                       <seq>{'         || :search_string || '}</seq>
    10                       <seq>'         || :search_string || '%</seq>
    11                       <seq>%'         || :search_string || '%</seq>
    12                       <seq>fuzzy({' || :search_string || '},1,100,WEIGHT)</seq>
    13                     </progression>
    14                  </textquery>
    15                   </QUERY>', 1 ) > 0
    16            order  by score(1) desc, this_.NAME_C)
    17  where  rownum < 21
    18  /
      SCORE(1)         ID NAME_C               URI_C
            76          4 ABB                  http://www.abb.de
            76          1 ABB Company Mgmt     http://www.abb-company-mgmt.de
            51          2 Dr. Abbas Ming       http://www.dr-abbas-ming.de
            26          3 SABBATA United       http://www.sabbata-united.de
             4          9 EBB                  fuzzy test
    SCOTT@10gXE> EXEC :search_string := 'and'
    PL/SQL procedure successfully completed.
    SCOTT@10gXE> /
      SCORE(1)         ID NAME_C               URI_C
            76          8 AND                  http://www.and.de
            76          5 AND Company Mgmt     http://www.and-company-mgmt.de
            51          6 Dr. Andas Ming       http://www.dr-andas-ming.de
            26          7 SANDATA United       http://www.sandata-united.de
             5         10 OND                  fuzzy test
    SCOTT@10gXE>

  • Converting Oracle XML Query Result in Java String by using XSU

    Hi,
    I have a problem by converting Oracle XML Query Result in Java
    String by using XSU. I use XSU for Java.
    For example:
    String datum=new OracleXMLQuery(conn,"Select max(ps.datum) from
    preise ps where match='"+args[0]+"'");
    String datum1=datum;
    I become the following error:
    Prototyp.java:47: Incompatible type for declaration. Can't
    convert oracle.xml.sql.query.OracleXMLQuery to java.lang.String.
    Can somebody tell me a method() for converting to solve my
    problem??????
    Thanks

    Hmmm.. Pretty basic just look at the example:
    OracleXMLQuery qry = new OracleXMLQuery(conn,"Select max(ps.datum) from preise ps where match='"+args[0]+"'");
    String xmlString = qry.getXMLString();
    Hi,
    I have a problem by converting Oracle XML Query Result in Java
    String by using XSU. I use XSU for Java.
    For example:
    String datum=new OracleXMLQuery(conn,"Select max(ps.datum) from
    preise ps where match='"+args[0]+"'");
    String datum1=datum;
    I become the following error:
    Prototyp.java:47: Incompatible type for declaration. Can't
    convert oracle.xml.sql.query.OracleXMLQuery to java.lang.String.
    Can somebody tell me a method() for converting to solve my
    problem??????
    Thanks

  • Syntax error in Merge Query

    This is the first time i am using Merge Query and the query is
    ;MERGE saSalesStockRecevedSub AS T
       USING @tableSRN AS S
       ON (T.prodCode=S.prodCode AND T.packtypeID=S.packtypeID AND T.batchCode=S.batchCode and T.stockReceiveMainID=S.stockReceiveMainID)
    WHEN NOT MATCHED BY T
        THEN
        INSERT(stockReceiveMainID, prodCode, packtypeID, batchCode, quantityClaim, quantityReceived,reasonId, qQuantity, saleableQty, mfgDefect, slDamageQty, nonSaleableQty, damageQty, breakageQty, leakageQty, expiryQty, remarks,activeStatus,cnCreateSl,cnCreateNsl)
        VALUES(S.stockReceiveMainID, S.prodCode, S.packtypeID, S.batchCode, S.quantityClaim, S.quantityReceived,S.reasonId, S.qQuantity, S.saleableQty, S.mfgDefect, S.slDamageQty, S.nonSaleableQty, S.damageQty, S.breakageQty, S.leakageQty, S.expiryQty,
    S.remarks,'ACTIVE','FALSE','FALSE')
    WHEN MATCHED
        THEN
        UPDATE SET T.quantityClaim=S.quantityClaim, T.quantityReceived=S.quantityReceived,T.reasonId=S.reasonId, T.qQuantity=S.qQuantity, T.saleableQty=S.saleableQty, T.mfgDefect=S.mfgDefect, T.slDamageQty=S.slDamageQty, T.nonSaleableQty=S.nonSaleableQty,
    T.damageQty=S.damageQty, T.breakageQty=S.breakageQty, T.leakageQty=S.leakageQty, T.expiryQty=S.expiryQty, T.remarks=S.remarks
    WHEN NOT MATCHED BY S
        THEN
        DELETE ;
    It showing incorrect syntax near 'T'.
    Please help me.
    Thanks

    Here below is the complete code, hope it will work with you. 
    You should use the key word source and target instead of using S and T
    MERGE saSalesStockRecevedSub AS T
       USING tableSRN AS S
       ON (T.prodCode=S.prodCode AND T.packtypeID=S.packtypeID AND T.batchCode=S.batchCode and T.stockReceiveMainID=S.stockReceiveMainID)
    WHEN NOT MATCHED BY TARGET
        THEN 
        INSERT(stockReceiveMainID, prodCode, packtypeID, batchCode, quantityClaim, quantityReceived,reasonId, qQuantity, saleableQty, mfgDefect, slDamageQty, nonSaleableQty, damageQty, breakageQty, leakageQty, expiryQty, remarks,activeStatus,cnCreateSl,cnCreateNsl) 
        VALUES(S.stockReceiveMainID, S.prodCode, S.packtypeID, S.batchCode, S.quantityClaim, S.quantityReceived,S.reasonId, S.qQuantity, S.saleableQty, S.mfgDefect, S.slDamageQty, S.nonSaleableQty, S.damageQty, S.breakageQty, S.leakageQty, S.expiryQty,
    S.remarks,'ACTIVE','FALSE','FALSE')
    WHEN MATCHED  
        THEN 
        UPDATE SET T.quantityClaim=S.quantityClaim, T.quantityReceived=S.quantityReceived,T.reasonId=S.reasonId, T.qQuantity=S.qQuantity, T.saleableQty=S.saleableQty, T.mfgDefect=S.mfgDefect, T.slDamageQty=S.slDamageQty, T.nonSaleableQty=S.nonSaleableQty,
    T.damageQty=S.damageQty, T.breakageQty=S.breakageQty, T.leakageQty=S.leakageQty, T.expiryQty=S.expiryQty, T.remarks=S.remarks
    WHEN NOT MATCHED BY SOURCE
        THEN 
        DELETE ;
    Working as a Senior Database Analyst & Architect at Ministry of Higher Education in KSA

  • Oracle text query

    Hi,
    I have a View object with various attributes (eg, name1, name2, name3, address1, address2, address3 etc). A query/table component based on this view object works just fine. However, I wish to replace name1, name2, name3 and other attributes in the query with just 'name'. These attributes are still to be shown in the result table. This new 'name' attribute will be used in an Oracle Text query clause, instead of individual searches on each attribute.
    My plan was to simply make the various name1, name2 etc attributes non-'queryable' in the View def to hide them from the query. Then I'd add a transient 'name' attribute. My hope was, that I could override the getWhereClause() in the ViewObjectImpl and simply tack on the oracle text clause to the WHERE (example below):
    WHERE CONTAINS (
    SOMECOLUMN,
                '<query>
       <textquery lang="ENGLISH" grammar="CONTEXT">TRANSIENT_ATTR_VALUE
    ..... Oracle Text query grammar stuff here ....  </query>') > 0How do I access the transient value in the ViewObjectImpl to add the above SQL? Or am I going about this in completely the wrong way?
    thanks,
    Barry.

    Based on what I found in
    http://www.oracle.com/technology/oramag/oracle/09-nov/o69frame.html?_template=/ocom/print
    and
    http://blogs.oracle.com/smuenchadf/examples/
    136.     Introducing a Checkbox to Toggle a Custom SQL Predicate on an LOV's Search Form. [11.1.1.0.0] 19-NOV-2008
    I have the following implementation, which seems to work. Does anyone see any problems with this?
    With regard to SQL injection, does ViewCriteriaItem sanitise the 'val' from the query, or should I do that manually here myself?
        @Override
        public java.lang.String getCriteriaItemClause(ViewCriteriaItem vci) {
            if ("OraTextTransientAttrib".equals(vci.getAttributeDef().getName())) {
                if (vci.getViewCriteria().isCriteriaForQuery()) {
                    String val = (String)vci.getValue();
                    logger.debug("Doing oracle text name search on '" + val + "'");
                    // simplified version of my oracle text query
                    return "CONTAINS ('<query>..... " + val + "....</query>') > 0 ";
                } else {
                    // SQL predicate for no changes to the results
                    // spaces needed if you have several of these blocks
                    return " 1=1 ";
            // other blocks for other similar oracle text attribs
            return super.getCriteriaItemClause(vci);
        }

  • Need Help In Merge query

    Hi ,
    i m using merge query .
    below is my query .
    MERGE INTO tbltmonthlysales A
    USING
    (select DISTINCT 'JAN-2011' MON_YYYY,distributorname DISTRIBUTORNAME From SYN_VWABS) B
    ON (a.distributorname = B.distributorname)
    WHEN NOT MATCHED THEN
    INSERT (A.MON_YYYY,A.distributorname) VALUES (B.MON_YYYY,B.DISTRIBUTORNAME);
    ------Now Firing this query ---
    1)
    SQL> MERGE INTO tbltmonthlysales A
    2 USING
    3 (select DISTINCT 'JAN-2011' MON_YYYY,distributorname DISTRIBUTORNAME From SYN_VWABS) B
    4 ON (a.distributorname = B.distributorname)
    5 WHEN NOT MATCHED THEN
    6 INSERT (A.MON_YYYY,A.distributorname) VALUES (B.MON_YYYY,B.DISTRIBUTORNAME);
    INSERT (A.MON_YYYY,A.distributorname) VALUES (B.MON_YYYY,B.DISTRIBUTORNAME)
    ERROR at line 6:
    ORA-00904: "B"."DISTRIBUTORNAME": invalid identifier
    now i m createing one table
    create table test2 as select * from SYN_VWABS
    2)
    SQL> MERGE INTO tbltmonthlysales A
    2 USING
    3 (select DISTINCT 'JAN-2011' MON_YYYY,distributorname DISTRIBUTORNAME From test2) B
    4 ON (a.distributorname = B.distributorname)
    5 WHEN NOT MATCHED THEN
    6 INSERT (A.MON_YYYY,A.distributorname) VALUES (B.MON_YYYY,B.DISTRIBUTORNAME);
    INSERT (A.MON_YYYY,A.distributorname) VALUES (B.MON_YYYY,B.DISTRIBUTORNAME)
    71 rows merged.
    My question is why my 1) query is not executing?

    thanks your efforts are apriciated but its not working
    see i have created view as per ur suggestion,
    create or replace view vwabc as
    SELECT x.accountnumber accountnumber,
    distributorname distributorname,
    staffname staffname,
    resellerno resellerno,
    resellername resellername, resellercreatedate resellercreatedate, customerno customerno, custmername custmername,
    customeractivationdate customeractivationdate, childaccountnumber childaccountnumber, childaccountname childaccountname,
    childactivationdate childactivationdate, resellerstaff resellerstaff
    --x.accountstaffid Disaccountstaffid,
    --y.accountstaffid resaccountstaffid
    FROM (SELECT Y.RELATIONACCOUNTNUMBER accountnumber, x.NAME distributorname, staffname,
    y.accountnumber resellerno, y.accountid resaccountid,
    x.accountstaffid
    FROM ((SELECT a.accountid, b.accountstaffid, a.NAME,
    b.NAME staffname, a.accountnumber
    FROM tblmaccount a, tblmaccountstaff b
    WHERE a.accounttypeid = 'ACT04' AND a.accountid = b.owneraccountid(+))
    UNION ALL
    (SELECT a.accountid, NULL, a.NAME, NULL, a.accountnumber
    FROM tblmaccount a
    WHERE a.accounttypeid = 'ACT04'
    AND EXISTS (SELECT 1
    FROM tblmaccountstaff c
    WHERE c.owneraccountid = a.accountid))) x,
    tblmaccountaccountrel y
    WHERE NVL (x.accountstaffid, '-') = NVL (y.accountstaffid(+), '-')
    AND x.accountid = y.relationaccountid(+)
    --and x.accountid = 'ACC000537173'
    ) x,
    (SELECT x.accountnumber, x.NAME resellername, resellerstaff,
    x.accountstaffid, y.accountnumber customerno,
    ta.NAME custmername, ta.accountid,
    ta.activationdate customeractivationdate,
    y.relationaccountid, cust.accountnumber childaccountnumber,
    cust.NAME childaccountname,
    TRUNC (cust.activationdate) childactivationdate,
    x.resellercreatedate
    FROM ((SELECT a.accountid, b.accountstaffid, a.NAME,
    b.NAME resellerstaff, a.accountnumber,
    TRUNC (a.createdate) resellercreatedate
    FROM tblmaccount a, tblmaccountstaff b
    WHERE a.accounttypeid = 'ACT03' AND a.accountid = b.owneraccountid(+))
    UNION ALL
    (SELECT a.accountid, NULL, a.NAME, NULL, a.accountnumber,
    TRUNC (a.createdate) resellercreatedate
    FROM tblmaccount a
    WHERE a.accounttypeid = 'ACT03'
    AND EXISTS (SELECT 1
    FROM tblmaccountstaff c
    WHERE c.owneraccountid = a.accountid))) x,
    tblmaccountaccountrel y,
    tblmaccount ta,
    tblmaccount cust
    WHERE NVL (x.accountstaffid, '-') = NVL (y.accountstaffid, '-')
    AND x.accountid = y.relationaccountid(+)
    AND y.accountid = ta.accountid(+)
    AND ta.accountnumber = cust.parentaccountnumber
    --and x.accountid = 'ACC000537856'
    ) y
    WHERE x.resaccountid = y.relationaccountid(+)
    Now firing Merge,
    SQL> MERGE INTO tbltmonthlysales A
    2 USING
    3 (select DISTINCT MON_YYYY ,distributorname From vwabc) B
    4 ON (a.distributorname = B.distributorname)
    5 WHEN NOT MATCHED THEN
    6 INSERT (A.MON_YYYY,A.distributorname) VALUES (B.MON_YYYY,B.DISTRIBUTORNAME);
    (select DISTINCT MON_YYYY ,distributorname From vwabc) B
    ERROR at line 3:
    ORA-00904: "MON_YYYY": invalid identifier
    still error :(

  • Issue with "read by other session" and a parallel MERGE query

    Hi everyone,
    we have run into an issue with a batch process updating a large table (12 million rows / a few GB, so it's not that large). The process is quite simple - load the 'increment' from a file into a working table (INCREMENT_TABLE) and apply it to the main table using a MERGE. The increment is rather small (usually less than 10k rows), but the MERGE runs for hours (literally) although the execution plan seems quite reasonable (can post it tomorrow, if needed).
    The first thing we've checked is AWR report, and we've noticed this:
    Top 5 Timed Foreground Events
    Event     Waits     Time(s)     Avg wait (ms)     % DB time     Wait Class
    DB CPU           10,086           43.82     
    read by other session     3,968,673     9,179     2     39.88     User I/O
    db file scattered read     1,058,889     2,307     2     10.02     User I/O
    db file sequential read     408,499     600     1     2.61     User I/O
    direct path read     132,430     459     3     1.99     User I/OSo obviously most of the time was consumed by "read by other session" wait event. There were no other queries running at the server, so in this case "other session" actually means "parallel processes" used to execute the same query. The main table (the one that's updated by the batch process) has "PARALLEL DEGREE 4" so Oracle spawns 4 processes.
    I'm not sure how to fix this. I've read a lot of details about "read by other session" but I'm not sure it's the root cause - in the end, when two processes read the same block, it's quite natural that only one does the physical I/O while the other waits. What really seems suspicious is the number of waits - 4 million waits means 4 million blocks, 8kB each. That's about 32GB - the table has about 4GB, and there are less than 10k rows updated. So 32 GB is a bit overkill (OK, there are indexes etc. but still, that's 8x the size of the table).
    So I'm thinking that the buffer cache is too small - one process reads the data into cache, then it's removed and read again. And again ...
    One of the recommendations I've read was to increase the PCTFREE, to eliminate 'hot blocks' - but wouldn't that make the problem even worse (more blocks to read and keep in the cache)? Or am I completely wrong?
    The database is 11gR2, the buffer cache is about 4GB. The storage is a SAN (but I don't think this is the bottleneck - according to the iostat results it performs much better in case of other batch jobs).

    OK, so a bit more details - we've managed to significantly decrease the estimated cost and runtime. All we had to do was a small change in the SQL - instead of
    MERGE /*+ parallel(D DEFAULT)*/ INTO T_NOTUNIFIED_CLIENT D /*+ append */
      USING (SELECT
          FROM TMP_SODW_BB) S
      ON (D.NCLIENT_KEY = S.NCLIENT_KEY AND D.CURRENT_RECORD = 'Y' AND S.DIFF_FLAG IN ('U', 'D'))
      ...(which is the query listed above) we have done this
    MERGE /*+ parallel(D DEFAULT)*/ INTO T_NOTUNIFIED_CLIENT D /*+ append */
      USING (SELECT
          FROM TMP_SODW_BB AND DIFF_FLAG IN ('U', 'D')) S
      ON (D.NCLIENT_KEY = S.NCLIENT_KEY AND D.CURRENT_RECORD = 'Y')
      ...i.e. we have moved the condition from the MERGE ON clause to the SELECT. And suddenly, the execution plan is this
    OPERATION                           OBJECT_NAME             OPTIONS             COST
    MERGE STATEMENT                                                                 239
      MERGE                             T_NOTUNIFIED_CLIENT
        PX COORDINATOR
          PX SEND                       :TQ10000                QC (RANDOM)         239
            VIEW
              NESTED LOOPS                                      OUTER               239
                PX BLOCK                                        ITERATOR
                  TABLE ACCESS          TMP_SODW_BB             FULL                2
                    Filter Predicates
                      OR
                        DIFF_FLAG='D'
                        DIFF_FLAG='U'
                  TABLE ACCESS          T_NOTUNIFIED_CLIENT       BY INDEX ROWID    3
                    INDEX               AK_UQ_NOTUNIF_T_NOTUNI    RANGE SCAN        2
                      Access Predicates
                        AND
                          D.NCLIENT_KEY(+)=NCLIENT_KEY
                          D.CURRENT_RECORD(+)='Y'
                      Filter Predicates
                        D.CURRENT_RECORD(+)='Y' Yes, I know the queries are not exactly the same - but we can fix that. The point is that the TMP_SODW_BB table contains 1639 rows in total, and 284 of them match the moved 'IN' condition. Even if we remove the condition altogether (i.e. 1639 rows have to be merged), the execution plan does not change (the cost increases to about 1300, which is proportional to the number of rows).
    But with the original IN condition (that turns into an OR combination of predicates) in the MERGE ON clausule, the cost suddenly skyrockets to 990.000 and it's damn slow. It seems like a problem with cost estimation, because once we remove one of the values (so there's only one value in the IN clausule), it works fine again. So I guess it's a planner/estimator issue ...

  • Why oracle spatial query execute so slow???

    hi all,
    I have two oracle spatial table CHI_2007r2 and CHI_2008r2, each table has it's own spatial index,and each table has 2000 row record, Now execute this query,I can get the result soon,
    select /*+ ORDERED */ a.link_id from chi_2007r2 a,chi_2008r2 b where a.link_id=b.link_id and sdo_relate(a.geom,b.geom,'mask=INSIDE querytype=WINDOW')='TRUE';
    But I execute the query by geom only,it will take so long time! query(3 more hours):
    select /*+ ORDERED */ a.link_id,b.link_id from chi_2007r2 a,chi_2008r2 b where sdo_relate(a.geom,b.geom,'mask=INSIDE querytype=WINDOW')='TRUE';
    I don't upderstand...
    thanks
    David

    Because in the first statement
    select /*+ ORDERED */ a.link_id from chi_2007r2 a,chi_2008r2 b where a.link_id=b.link_id and sdo_relate(a.geom,b.geom,'mask=INSIDE querytype=WINDOW')='TRUE'; you are joining the two tables while in the second statement
    select /*+ ORDERED */ a.link_id,b.link_id from chi_2007r2 a,chi_2008r2 b where sdo_relate(a.geom,b.geom,'mask=INSIDE querytype=WINDOW')='TRUE';you are doing a cartesian merge first because there is no join between a and b other than te sdo_relate which will be calculated for every row combination you get.
    But I think you'd be better off posting in the {forum:id=76} forum.
    Best regards,
    PP
    Edited by: porzer on Jan 15, 2009 10:34 AM

Maybe you are looking for