Inserting values using merge

Hi everyone,
I need help with inserting values using merge.
* I need to check all the units in a parent category. For example, NF_ARTICLECATEGORYID = 7462 is a parent category.
* Im going to compare all the units in the parent category(7642) to the units in a subcategory (8053).
* If the units in parent category(7642) is not present in the subcategory(8053) then the units will be inserted in the same table.
table structure:
Table name : ARTICLECATEGORYACCESS
Fields: IP_ARTICLECATEGORYACCESSID
NF_ARTICLECATEGORYID
NF_UNITID
NF_USERID
N_VIEW
N_EDIT
Sample data:
CREATE TABLE articlecategoryaccess (
IP_ARTICLECATEGORYACCESSID NUMBER(5),
NF_ARTICLECATEGORYID NUMBER (10),
NF_UNITID NUMBER (10),
NF_USERID NUMBER (10)
N_VIEW INT,
N_EDIT INT);
INSERT INTO articlecategoryaccess VALUES (255583, 7642, 29727, NULL, 1 ,1);
INSERT INTO articlecategoryaccess VALUES (243977,7642,29728, NULL, 1 ,1);
INSERT INTO articlecategoryaccess VALUES (240770,7642,29843, NULL, 1 ,1);
INSERT INTO articlecategoryaccess VALUES (243413,7642,29844, NULL, 1 ,1);
INSERT INTO articlecategoryaccess VALUES (274828,7642,44849, NULL, 1 ,1);
INSERT INTO articlecategoryaccess VALUES (274828,8053,44849, NULL, 1 ,1);
Units ID 29727, 29728, 29843, 29844, 44849 has access to parent category 7642.
The units id 29727, 29728, 29843, 29844 dont have access to subcategory 8053.
29727, 29728, 29843, 29844 should be inserted in the same table and will have an access to 8053.
After they are inserted, it should look like this
IP_ARTICLECATEGORYACCESSID     NF_ARTICLECATEGORYID     NF_UNITID NF_USERID N_VIEW N_EDIT
255583     7642     29727 null 1 1
243977     7642     29728 null 1 1
240770     7642     29843 null 1 1
243413     7642     29844 null 1 1
274828     7642     44849 null 1 1
new value     8053     44849 null 1 1
new value     8053     29843 null 1 1
new value     8053     29844 null 1 1
new value     8053     29728 null 1 1
new value     8053     29727 null 1 1
NOTE: IP_ARTICLECATEGORYACCESSID is a sequence and it should be unique
DECLARE
BEGIN
MERGE INTO articlecategoryaccess b
USING (SELECT *
FROM articlecategoryaccess c
WHERE nf_articlecategoryid = 7642
MINUS
SELECT *
FROM articlecategoryaccess c
WHERE nf_articlecategoryid = 8053) e
ON (1 = 2)
WHEN NOT MATCHED THEN
INSERT (b.ip_articlecategoryaccessid, b.nf_articlecategoryid, b.nf_unitid, b.NF_USERID, b.N_VIEW, b.N_EDIT)
VALUES (articlecategoryaccessid_seq.nextval, 8053, e.nf_unitid, null, 1, 1);
END;
i got an error after running the script:
*Cause:    An UPDATE or INSERT statement attempted to insert a duplicate key.
For Trusted Oracle configured in DBMS MAC mode, you may see
this message if a duplicate entry exists at a different level.
*Action:   Either remove the unique restriction or do not insert the key.
why would it be duplicated? its a sequence and its unique.. I dont know, maybe there is something wrong my script..
Any help is appreciated..
Ed

Ed,
1. What is the current value of the Sequence? Does the current value of sequence exist in the table? If yes, then increment the sequence to a value that is not present in the Table.
2. Do you have any unique constraint on any of the columns that you are inserting?
I have to ask you again, Why are you insisting on Merge statement when a simple Insert can do the job for you? Don't you feel that the below specified Merge statement is making things look more Complicated than they actually are, do you?
Think on it and then proceed. I hope these pointers help you to resolve the issue.
Regards,
P.

Similar Messages

  • XML insertion/updation using merge and generate sequence number

    Hi,
    I am working on Oracle 11g.
    I have a doubt with XML load.
    I get an xml and I have to insert or update data into a table A. This I can achieve using MERGE statement.
    But there is one column in Table A, that I need to populate with a sequence number, based on the data sent in the xml.
    The xml does not send this column data.
    And I have to make sure the sequence is created based on the order in which records are present in xml.
    For example the MERGE is inserting five rows and then updating next two rows and again inserting 3 rows from xml into table A. The sequence number should be created in the same order for the column in table A.
    Also for each new xml, the sequence starts with 1 and ends with the number of records in the xml. So I cannot create a sequence and use seq.nextval.
    Please let me know, there is a way of achieveing this.
    Thank you!
    Edited by: 934451 on Aug 8, 2012 6:33 AM
    Edited by: 934451 on Aug 8, 2012 6:50 AM

    Hi,
    Following up on your previous thread : {thread:id=2403469}
    You can use the FOR ORDINALITY clause in XMLTable to generate the required sequence :
    MERGE INTO target_table t
    USING (
      SELECT x.seq_num, x.pk_id, x.col1, x.col2, ...
      FROM XMLTable(
             '/root/record'
             passing my_xml_doc
             columns seq_num FOR ORDINALITY
                   , pk_id   number       path 'ID'
                   , col1    varchar2(30) path 'COL1'
                   , col2    varchar2(30) path 'COL2'
           ) x
    ) src
    ON ( t.pk_id = src.pk_id )
    WHEN MATCHED THEN UPDATE
    SET t.seq_num = src.seq_num
       , t.col1 = src.col1
       , t.col2 = src.col2
    WHEN NOT MATCHED THEN INSERT
    (seq_num, pk_id, col1, col2, ...)
    VALUES (src.seq_num, src.pk_id, src.col1, src.col2, ...)
    ;

  • How to insert values using pushputtons in text item & fetch data based on

    Dear friends,
    I want to insert values in the Text item using pushbutton e.g to insert 05CST884 into text item using pushbuttons '0' '5' 'C' 'S' 'T' '8' '8' '4' (alpha numeric buttons) in the layout editor and then fetch data based on the number entered with that of one in the table in the another text item2 in the layout editor.
    Suggestions regarding how to develop and use effective triggers are welcome.

    At the block level (for the control block where all your push buttons are, let's call it block1) create a WHEN-BUTTON-PRESSED trigger. Your [A-Z] and [0-9] buttons should be on a dedicated non-database datablock to reduce problems. As stated previously, this trigger should just contain the code:
    :block2.text_item := :block2.text_item||get_item_property(:system.trigger_item, label);
    Also on the pushbutton block, create a backspacve button with its own dedicated WHEN-BUTTON-PRESSED trigger containing:
    if length(:block2.text_item) > 0 then :block2.text_item := substr(:block2.text_item, 1, length(:block2.text_item)); end if;
    This will hopefully erase the last character entered.
    block2 should be based on the database table (see Property Palette --> Database) you wish to query and text_item should be based on the database item which contains the code you entered. All the other database items you wish to displayshould also be added to block2.
    Add another FIND push button to block1 with the code:
    go_block('block2');
    execute_query;
    Without writing the whole thing for you, I'd suggest you get a decent Forms tutorial book to guide you through the basics (Oracle Forms Developers Handbook).

  • When I use Merge duplicate Values

    Hi
    When I use MERGE for to INSERT It is duplicating values, I put condition in ON
    MERGE                         /*+  append nologging */ INTO sysadm.ps_loc_item_sn_zz2 t3
       USING (WITH tmp_ps_loc_item AS
                   (SELECT loc_cntr_id_sn, setid, companyid, effdt, setid_product, loc_product_sn,
                           ROW_NUMBER () OVER (PARTITION BY loc_cntr_id_sn, setid, companyid, effdt, setid_product, loc_product_sn ORDER BY linha)
                                                                                          seqno_item_sn,
                           loc_item_status, NULL ken_data_ativ_sn, NULL inactive_date_sn,
                           'LO' cntrct_origin_sn, SYSDATE row_added_dttm,
                           'CARGA PS 29052007' row_added_oprid, SYSDATE row_lastmant_dttm,
                           'CARGA PS 29052007' row_lastmant_oprid, 0 syncid, NULL syncdttm,
                           ken_component_sn
                      FROM (SELECT t1.*, ROWNUM linha
                              FROM sysadm.tmp_equip_crm t1,
                                   (SELECT     LEVEL l
                                          FROM DUAL
                                    CONNECT BY LEVEL <= 100)
                             WHERE l <= t1.qtd) )
              SELECT t2.loc_cntr_id_sn, t2.setid, companyid, effdt, setid_product, loc_product_sn,
                     t2.seqno_item_sn, loc_item_status, t5.ken_data_ativ_sn, inactive_date_sn,
                     cntrct_origin_sn, row_added_dttm, row_added_oprid, row_lastmant_dttm, syncid,
                     syncdttm, t2.ken_component_sn
                FROM tmp_ps_loc_item t2, sysadm.tmp_data_ativa t5
               WHERE t2.loc_cntr_id_sn = t5.loc_cntr_id_sn(+)
                 AND t2.ken_component_sn = t5.ken_component_sn(+)
                 AND t2.loc_item_status = t5.loc_item_status_sn(+)
                 AND t2.seqno_item_sn = t5.seqno_item_sn(+)) t4
       ON (    t3.loc_cntr_id_sn = t4.loc_cntr_id_sn
           AND t3.setid = t4.setid
           AND t3.companyid = t4.companyid
           AND t3.effdt = t4.effdt
           AND t3.setid_product = t4.setid_product
           AND t3.loc_product_sn = t4.loc_product_sn
           AND t3.seqno_item_sn = t4.seqno_item_sn)
       WHEN MATCHED THEN
          UPDATE
             SET t3.syncid = 0
       WHEN NOT MATCHED THEN
          INSERT (loc_cntr_id_sn, setid, companyid, effdt, setid_product, loc_product_sn, seqno_item_sn,
                  loc_item_status_sn, ken_data_ativ_sn, inactive_date_sn, cntrct_origin_sn,
                  row_added_dttm, row_added_oprid, row_lastmant_dttm, row_lastmant_oprid, syncid,
                  syncdttm)
          VALUES (t4.loc_cntr_id_sn, t4.setid, t4.companyid, t4.effdt, t4.setid_product,
                  t4.loc_product_sn, t4.seqno_item_sn, loc_item_status, t4.ken_data_ativ_sn,
                  t4.inactive_date_sn, t4.cntrct_origin_sn, t4.row_added_dttm, t4.row_added_oprid,
                  t4.row_lastmant_dttm, t4.ken_component_sn, t4.syncid, t4.syncdttm);

    I don't understand what you mean exactly?
    When an SQL statement encounters an error then all
    its work is rolled back ...
    So why do you expect that it worùs otherwise?simply
    WHEN MATCHED THEN      UPDATE         SET t3.syncid = 0Only

  • Insert with Select while Using Merge

    Actual Query
    MERGE INTO schema1.employees D
       USING (SELECT employee_id, salary, department_id FROM schema2.employees
       WHERE department_id = 80) S
       ON (D.employee_id = S.employee_id)
       WHEN MATCHED THEN
       UPDATE
       SET D.bonus = D.bonus + S.salary*.01
       WHERE (S.salary > 8000)
       WHEN NOT MATCHED THEN INSERT (D.employee_id, D.bonus)
       VALUES (S.employee_id, S.salary*.01)
       WHERE (S.salary <= 8000) Is there a possible way to write a select Query in Insert Statement while using Merge.
      WHEN NOT MATCHED THEN
       INSERT
       SELECT * FROM schema2.employees
       WHERE S.salary <= 8000;

    it works:
    MERGE INTO fifapps.tes2
    using dual
    on (1=2)
    when not matched then insert values(59,'yes');
    commit;or
    MERGE INTO fifapps.tes2
    using dual
    on (1=2)
    when not matched then insert values ((select 99 from dual),(select'weii' from dual));
    commit;Edited by: ʃʃp on Jun 13, 2012 2:03 AM
    Edited by: ʃʃp on Jun 13, 2012 2:03 AM

  • Unique constraint is not thrown when used MERGE INSERT (alone) via dblink.

    We found some interesting behaviour of unique constraint on Merge query when we use Merge When Not Matched Insert (no update query) via a dblink.
    In one Schema S1, on Table A1(c1,c2,c3) there is a unique constraint on column (c1,c2).
    Column c2 is nullable and has null for some records.
    Now i have a table A2 with same defintion as A1 in Schema S2.In S2 , i have a dblink of S1 as S1 itself.
    I have data in S2.A2. Here also i have some records with c2 as null and c1 matching with the data of S1.A1.
    Now from schema S2,
    I am using the following Merge Query,
    MERGE INTO S1.A1 target
    USING S2.A2 source
    ON (target.c1 = source.c1 and target.c2 = source.c2)
    WHEN NOT MATCHED
    INSERT (c1,c2,c3) values (source.c1, source.c2,source.c3)
    WHEN MATCHED
    UPDATE c3 = source.c3;
    Now when i execute this merge in schema S2,
    if i have some data in S1.A1 and S2.A2 having c1 as same and c2 as null, as oracle does not treat two nulls same, it goes for an insert, i have got unique constraint violated error.
    But if i execute MERGE INSERT alone, though that record is getting inserted , i am not getting unique constraint violated error.
    Oracle version we are using is 10g (10.2...).
    Is it a bug in oracle or what could have caused this behaviour.

    Dear,
    ERROR at line 1:
    ORA-00001: unique constraint (SYS_C00137508) violatedYou need to think about two things
    (a) read consistency : what was the situation of table_1 when the maching clause has been initially evaluated ; there were 0 rows matching which means the merge operation will be all insert
    (b) your matching clause has a problem : the join column must be unique in both tables otherwise the merge will be ambigous. You don't have a unique key on the source table
    (c) think that the merge operation will never insert id =1 and then update id = 1 within the same operation. This will never happen
    Hope this helps
    Mohamed Houri

  • Using Merge to Update to Insert, Update, and also deleting obsolete records

    Hi all!!!
    Suppose that a have the following table, called Orders:
    ORDERID        STATUS      PRICE
             1          0        100
             2          0        200
             3          0        300
             4          0        350
             5          0        390 Also, there is a procedure that will generate some data on a global temporary table, called Orders_Temp. This temporary table will be used to update the Orders table.+Orders+ have a trigger that will perform different operations when a Insert, Delete or Update command is performed.
    Consider that the Orders_Temp table have the following data after running a procedure that is responsible for updating orders data:
    ORDERID        STATUS      PRICE
             1          1        100
             2          2        200
             3          0        300
             5          0        390
             6          0        350 As you can see, orders 1 and 2 were updated. Order 3 and 5 were untouched, order 4 was deleted and order 6 was inserted. Merge will handle the correctly handle orders 1, 2, 3, 5 and 6, even though generating a update to orders 3 and 5, that were not changed.
    So, here are the questions:
    1) How could I delete the order 4 from Orders, since this order was not present on the Orders_Temp? Is there a way to use the merge command to do this?
    2) Is there any way to not generate a update operation for orders 3 and 5, that were not changed?
    I´m using Oracle 10.2 SE.
    Thanks a lot!
    Regis

    Hello G!
    Thank you so much for your help.
    Your code took only a modification:
    MERGE INTO orders tgt
    USING (SELECT A.*, 1 mask
              FROM orders_temp A
            UNION ALL
            SELECT A.*, 0
              FROM orders A
             WHERE NOT EXISTS
                     (SELECT 1
                        FROM orders_temp b
                       WHERE A.order_id = b.order_id)) src
        ON (tgt.order_id = src.order_id)
    WHEN MATCHED
    THEN
      UPDATE SET tgt.status = src.status, tgt.price = src.price
         /*WHERE src.mask = 1
           AND tgt.status != src.status
           AND tgt.price != src.price*/
      DELETE
         WHERE src.mask = 0
    WHEN NOT MATCHED
    THEN
      INSERT VALUES (src.order_id, src.status, src.priceWithout doing this, the DELETE WHERE clause was never called. After reading the docs, I found why:
    Specify the DELETE where_clause to clean up data in a table while populating or updating it. The only rows affected by this clause are those rows in the destination table that are updated by the merge operation. That is, the DELETE WHERE condition evaluates the updated value, not the original value that was evaluated by the UPDATE SET ... WHERE condition. If a row of the destination table meets the DELETE condition but is not included in the join defined by the ON clause, then it is not deleted. Any delete triggers defined on the target table will be activated for each row deletion.http://download.oracle.com/docs/cd/B19306_01/server.102/b14200/statements_9016.htm
    >
    From what I understand, if we restrict the records on update set_clause, the delete  where_clause will no be able to process because they were not touched. So, as as workaroud, I´m checking if the record was changed inside my trigger.
    Thanks a lot!
    Regards.
    Regis

  • How to receive parameters from a form and insert values in db using servlet

    Hi friends,
    My first question here.
    I'm trying to create a Servlet that takes input from a form and process it and insert it in database.tablename.
    My MAIN ISSUE IS WITH THE NUMBER OF COLUMNS THAT WOULD BE DYNAMIC AND THUS CANT RECEIVE THE PARAMETERS IN STATIC CODE.
    Here is the form code
    <%@page contentType="text/html" pageEncoding="UTF-8"%>
    <!DOCTYPE html>
    <form action="Test" method="post" />
    <table width="90%" border="1" cellspacing="1" cellpadding="1">
    <tr>
    <th scope="col">Student Name</th>
    <th scope="col">RollNo</th>
    <th scope="col">Java</th>
    <th scope="col">J2ee</th>
    </tr>
    <tr>
    <td><input type="text" name="studentname" /></td>
    <td><input type="text" name="rollno" /></td>
    <td><input type="text" name="java" /></td>
    <td><input type="text" name="j2ee" /></td>
    </tr>
    <tr>
    <td><input type="text" name="studentname" /></td>
    <td><input type="text" name="rollno" /></td>
    <td><input type="text" name="java" /></td>
    <td><input type="text" name="j2ee" /></td>
    </tr>
    <tr>
    <td><input type="text" name="studentname" /></td>
    <td><input type="text" name="rollno" /></td>
    <td><input type="text" name="java" /></td>
    <td><input type="text" name="j2ee" /></td>
    </tr>
    </table>
    <input type ="submit" value="insert values in the database now"/>
    </form>
    </html>
    And here is the Servlet
    import javax.servlet.*;
    import javax.servlet.http.*;
    import java.sql.*;
    import java.io.*;
    public class Test extends HttpServlet {
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
    String title = "Module: Process Result Values from previous page";
    out.println("<html>\n" +
    "<head><title>" + title + "</title></head>\n" +
    "<body>");
              try
                   Class.forName("com.mysql.jdbc.Driver");
                   Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/","root", "root");
                   Statement s = con.createStatement();
    ResultSet res = s.executeQuery("SELECT * FROM dbname.tablename");
    ResultSetMetaData rmeta=res.getMetaData();
    int noofcolumns=rmeta.getColumnCount();
                   if(!con.isClosed())
              catch(Exception e)
    System.out.println("Exception"+e);
    out.println(e);
    if(connectionFlag==1)
    out.println("</body></html>");
    doGet(request, response);
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
    This is the basic code structure and I'm trying to figure out this special case with handling the multiple parameters:
    1. I dont' want to use String []a=request.getParameterValues("studentname"); as hard code. The reason being the number of rows will be diyamic and I would like to get the column name and then then use an array of string to take values. But how can I connect these to form a query so that the rows goes on inserted one after other.
    Thanks,
    Mashall

    Thank you for your help.
    I'm something close to it but this segment of code throws a NullPointerException Error. I counted number of rows and columns using the methods getColumnCount() and getColumnName(i).
    ResultSetMetaData md = res.getMetaData(); //Get meta data for the resultset
    int noofcolumns=md.getColumnCount();
    out.println("<br />Number of columns in table (including name and roll number) :::: "+noofcolumns+"<br />");
    for(int i=1;i<=noofcolumns;i++) // access column 1....n
    String columnname = md.getColumnName(i); // get name of column 1....n
    out.println("<br />Current column name ::: "+columnname+"<br />"); //check if the name appear correct.
    String []columndata = request.getParameterValues(columnname); //Get raw value in array
    for(int j=1;j<=rows;j++) // here rows is number of rows in each column
    out.println("To be inserted: <b>"+columndata[j]+"</b> in Row ::: "+j+"<br />");
    //The line above thows null pointer exception.
    }

  • How to insert values in table using ADF Task flow? I am not able to bind CreateInsert on my first page fragement

    Hi,
    In Jdeveloper 12c I am trying to create a task flow where I have taken 3 pages to insert values in a table. On first page when I put data control of 2 columns as input with label, then on bindings tab I created an action as CreateInsert.
    Now when I am trying to create invoke action in executables then this option is not available.
    How can I create this task flow where values can be inserted in the table on the 3rd page fragment on commit button???
    All 3 pages have data control input boxes to insert values in the table.

    Hi,
    Right click on the task flow page activity, click create page def and add there. If your activity is a page, then you can select the page and generate the pagedef as well.
    Then you can add the executables.
    Thanks.

  • Restful service unable to insert data using PL/SQL.

    Hi all,
    Am running: AL 2.01 standalone mode on OEL 4.8 in VM box A.
    Oracle database 10.2.0.4 with Apex 4.2.0.00.27 on OEL4.8 in VM box B.
    Able to performed oracle.example.hr Restful services with no problem.
    Unable to insert data using AL 2.0.1 but works on AL 1.1.4.
    which uses the following table (under schema: scott):
    create table json_demo ( title varchar2(20), description varchar2(1000) );
    grant all on json_demo to apex_public_user; and below procedure ( scott's schema ):
    CREATE OR REPLACE
    PROCEDURE post(
        p_url     IN VARCHAR2,
        p_message IN VARCHAR2,
        p_response OUT VARCHAR2)
    IS
      l_end_loop BOOLEAN := false;
      l_http_req utl_http.req;
      l_http_resp utl_http.resp;
      l_buffer CLOB;
      l_data       VARCHAR2(20000); 
      C_USER_AGENT CONSTANT VARCHAR2(4000) := 'Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)';
    BEGIN
      -- source: http://awads.net/wp/2005/11/30/http-post-from-inside-oracle/
      -- Ask UTL_HTTP not to raise an exception for 4xx and 5xx status codes,
      -- rather than just returning the text of the error page.
      utl_http.set_response_error_check(false);
      -- Begin the post request
      l_http_req := utl_http.begin_request (p_url, 'POST', utl_http.HTTP_VERSION_1_1);
      -- Set the HTTP request headers
      utl_http.set_header(l_http_req, 'User-Agent', C_USER_AGENT);
      utl_http.set_header(l_http_req, 'content-type', 'application/json;charset=UTF-8');
      utl_http.set_header(l_http_req, 'content-length', LENGTH(p_message));
      -- Write the data to the body of the HTTP request
      utl_http.write_text(l_http_req, p_message);
      -- Process the request and get the response.
      l_http_resp := utl_http.get_response (l_http_req);
      dbms_output.put_line ('status code: ' || l_http_resp.status_code);
      dbms_output.put_line ('reason phrase: ' || l_http_resp.reason_phrase);
      LOOP
        EXIT
      WHEN l_end_loop;
        BEGIN
          utl_http.read_line(l_http_resp, l_buffer, true);
          IF(l_buffer IS NOT NULL AND (LENGTH(l_buffer)>0)) THEN
            l_data    := l_data||l_buffer;
          END IF;
        EXCEPTION
        WHEN utl_http.end_of_body THEN
          l_end_loop := true;
        END;
      END LOOP;
      dbms_output.put_line(l_data);
      p_response:= l_data;
      -- Look for client-side error and report it.
      IF (l_http_resp.status_code >= 400) AND (l_http_resp.status_code <= 499) THEN
        dbms_output.put_line('Check the URL.');
        utl_http.end_response(l_http_resp);
        -- Look for server-side error and report it.
      elsif (l_http_resp.status_code >= 500) AND (l_http_resp.status_code <= 599) THEN
        dbms_output.put_line('Check if the Web site is up.');
        utl_http.end_response(l_http_resp);
        RETURN;
      END IF;
      utl_http.end_response (l_http_resp);
    EXCEPTION
    WHEN OTHERS THEN
      dbms_output.put_line (sqlerrm);
      raise;
    END; and executing in sqldeveloper 3.2.20.09 when connecting directly to box B as scott:
    SET serveroutput ON
    DECLARE
      l_url      VARCHAR2(200)   :='http://MY_IP:8585/apex/demo';
      l_json     VARCHAR2(20000) := '{"title":"thetitle","description":"thedescription"}';
      l_response VARCHAR2(30000);
    BEGIN
      post( p_url => l_url, p_message =>l_json, p_response => l_response);
    END;which resulted in :
    anonymous block completed
    status code: 200
    reason phrase: OK
    with data inserted. Setup using 2.0.1
       Workspace : wsdemo
    RESTful Service Module:  demo/
              URI Template:      test
                    Method:  POST
               Source Type:  PL/SQLand executing in sqldeveloper 3.2.20.09 when connecting directly to box B as scott:
    SET serveroutput ON
    DECLARE
      l_url      VARCHAR2(200)   :='http://MY_IP:8585//apex/wsdemo/demo/test';
      l_json     VARCHAR2(20000) := '{"title":"thetitle","description":"thedescription"}';
      l_response VARCHAR2(30000);
    BEGIN
      post( p_url => l_url, p_message =>l_json, p_response => l_response);
    END;which resulted in :
    status code: 500
    reason phrase: Internal Server Error
    Listener's log:
    Request Path passes syntax validation
    Mapping request to database pool: PoolMap [_poolName=apex, _regex=null, _workspaceIdentifier=WSDEMO, _failed=false, _lastUpdate=1364313600000, _template=/wsdemo/, _type=BASE_PATH]
    Applied database connection info
    Attempting to process with PL/SQL Gateway
    Not processed as PL/SQL Gateway request
    Attempting to process as a RESTful Service
    demo/test matches: demo/test score: 0
    Choosing: oracle.dbtools.rt.resource.templates.jdbc.JDBCResourceTemplateDispatcher as current candidate with score: Score [handle=JDBCURITemplate [scopeId=null, templateId=2648625079503782|2797815111031405, uriTemplate=demo/test], score=0, scope=SecurityConfig [constraint=none, realm=NONE, logonConfig=LogonConfig [logonForm=null, logonFailed=null]], originsAllowed=[], corsEnabled=true]
    Determining if request can be dispatched as a Tenanted RESTful Service
    Request path has one path segment, continuing processing
    Tenant Principal already established, cannot dispatch
    Chose oracle.dbtools.rt.resource.templates.jdbc.JDBCResourceTemplateDispatcher as the final candidate with score: Score [handle=JDBCURITemplate [scopeId=null, templateId=2648625079503782|2797815111031405, uriTemplate=demo/test], score=0, scope=SecurityConfig [constraint=none, realm=NONE, logonConfig=LogonConfig [logonForm=null, logonFailed=null]], originsAllowed=[], corsEnabled=true] for: POST demo/test
    demo/test is a public resource
    Using generator: oracle.dbtools.rt.plsql.AnonymousBlockGenerator
    Performing JDBC request as: SCOTT
    Mar 28, 2013 1:29:28 PM oracle.dbtools.common.jdbc.JDBCCallImpl execute
    INFO: Error occurred during execution of: [CALL, begin
    insert into scott.json_demo values(/*in:title*/?,/*in:description*/?);
    end;, [title, in, class oracle.dbtools.common.stmt.UnknownParameterType], [description, in, class oracle.dbtools.common.stmt.UnknownParameterType]]with values: [thetitle, thedescription]
    Mar 28, 2013 1:29:28 PM oracle.dbtools.common.jdbc.JDBCCallImpl execute
    INFO: ORA-06550: line 1, column 6:
    PLS-00103: Encountered the symbol "" when expecting one of the following:
       begin case declare exit for goto if loop mod null pragma
       raise return select update while with <an identifier>
       <a double-quoted delimited-identifier> <a bind variable> <<
       close current delete fetch lock insert open rollback
       savepoint set sql execute commit forall merge pipe
    The symbol "" was ignored.
    ORA-06550: line 2, column 74:
    PLS-00103: Encountered the symbol "" when expecting one of the following:
       begin case declare end exception exit for goto if loop mod
       null pragma raise return select update while with
       <an identifier> <a double-quoted delimited-id
    java.sql.SQLException: ORA-06550: line 1, column 6:
    PLS-00103: Encountered the symbol "" when expecting one of the following:
       begin case declare exit for goto if loop mod null pragma
       raise return select update while with <an identifier>
       <a double-quoted delimited-identifier> <a bind variable> <<
       close current delete fetch lock insert open rollback
       savepoint set sql execute commit forall merge pipe
    The symbol "" was ignored.
    ORA-06550: line 2, column 74:
    PLS-00103: Encountered the symbol "" when expecting one of the following:
       begin case declare end exception exit for goto if loop mod
       null pragma raise return select update while with
       <an identifier> <a double-quoted delimited-id
            at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:447)
            at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:396)
            at oracle.jdbc.driver.T4C8Oall.processError(T4C8Oall.java:879)
            at oracle.jdbc.driver.T4CTTIfun.receive(T4CTTIfun.java:505)
            at oracle.jdbc.driver.T4CTTIfun.doRPC(T4CTTIfun.java:223)
            at oracle.jdbc.driver.T4C8Oall.doOALL(T4C8Oall.java:531)
            at oracle.jdbc.driver.T4CCallableStatement.doOall8(T4CCallableStatement.java:205)
            at oracle.jdbc.driver.T4CCallableStatement.executeForRows(T4CCallableStatement.java:1043)
            at oracle.jdbc.driver.OracleStatement.doExecuteWithTimeout(OracleStatement.java:1336)
            at oracle.jdbc.driver.OraclePreparedStatement.executeInternal(OraclePreparedStatement.java:3612)
            at oracle.jdbc.driver.OraclePreparedStatement.execute(OraclePreparedStatement.java:3713)
            at oracle.jdbc.driver.OracleCallableStatement.execute(OracleCallableStatement.java:4755)
            at oracle.jdbc.driver.OraclePreparedStatementWrapper.execute(OraclePreparedStatementWrapper.java:1378)
            at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
            at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
            at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
            at java.lang.reflect.Method.invoke(Method.java:597)
            at oracle.ucp.jdbc.proxy.StatementProxyFactory.invoke(StatementProxyFactory.java:242)
            at oracle.ucp.jdbc.proxy.PreparedStatementProxyFactory.invoke(PreparedStatementProxyFactory.java:124)
            at oracle.ucp.jdbc.proxy.CallableStatementProxyFactory.invoke(CallableStatementProxyFactory.java:101)
            at $Proxy46.execute(Unknown Source)
            at oracle.dbtools.common.jdbc.JDBCCallImpl.execute(JDBCCallImpl.java:44)
            at oracle.dbtools.rt.plsql.AnonymousBlockGenerator.generate(AnonymousBlockGenerator.java:176)
            at oracle.dbtools.rt.resource.templates.v2.ResourceTemplatesDispatcher$HttpResourceGenerator.response(ResourceTemplatesDispatcher.java:309)
            at oracle.dbtools.rt.web.RequestDispatchers.dispatch(RequestDispatchers.java:88)
            at oracle.dbtools.rt.web.HttpEndpointBase.restfulServices(HttpEndpointBase.java:412)
            at oracle.dbtools.rt.web.HttpEndpointBase.service(HttpEndpointBase.java:162)
            at javax.servlet.http.HttpServlet.service(HttpServlet.java:820)
            at com.sun.grizzly.http.servlet.ServletAdapter$FilterChainImpl.doFilter(ServletAdapter.java:1059)
            at com.sun.grizzly.http.servlet.ServletAdapter$FilterChainImpl.invokeFilterChain(ServletAdapter.java:999)
            at com.sun.grizzly.http.servlet.ServletAdapter.doService(ServletAdapter.java:434)
            at oracle.dbtools.standalone.SecureServletAdapter.doService(SecureServletAdapter.java:65)
            at com.sun.grizzly.http.servlet.ServletAdapter.service(ServletAdapter.java:379)
            at com.sun.grizzly.tcp.http11.GrizzlyAdapter.service(GrizzlyAdapter.java:179)
            at com.sun.grizzly.tcp.http11.GrizzlyAdapterChain.service(GrizzlyAdapterChain.java:196)
            at com.sun.grizzly.tcp.http11.GrizzlyAdapter.service(GrizzlyAdapter.java:179)
            at com.sun.grizzly.http.ProcessorTask.invokeAdapter(ProcessorTask.java:849)
            at com.sun.grizzly.http.ProcessorTask.doProcess(ProcessorTask.java:746)
            at com.sun.grizzly.http.ProcessorTask.process(ProcessorTask.java:1045)
            at com.sun.grizzly.http.DefaultProtocolFilter.execute(DefaultProtocolFilter.java:228)
            at com.sun.grizzly.DefaultProtocolChain.executeProtocolFilter(DefaultProtocolChain.java:137)
            at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:104)
            at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:90)
            at com.sun.grizzly.http.HttpProtocolChain.execute(HttpProtocolChain.java:79)
            at com.sun.grizzly.ProtocolChainContextTask.doCall(ProtocolChainContextTask.java:54)
            at com.sun.grizzly.SelectionKeyContextTask.call(SelectionKeyContextTask.java:59)
            at com.sun.grizzly.ContextTask.run(ContextTask.java:71)
            at com.sun.grizzly.util.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:532)
            at com.sun.grizzly.util.AbstractThreadPool$Worker.run(AbstractThreadPool.java:513)
            at java.lang.Thread.run(Thread.java:662)
    Error during evaluation of resource template: ORA-06550: line 1, column 6:
    PLS-00103: Encountered the symbol "" when expecting one of the following:
       begin case declare exit for goto if loop mod null pragma
       raise return select update while with <an identifier>
       <a double-quoted delimited-identifier> <a bind variable> <<
       close current delete fetch lock insert open rollback
       savepoint set sql execute commit forall merge pipe
    The symbol "" was ignored.
    ORA-06550: line 2, column 74:
    PLS-00103: Encountered the symbol "" when expecting one of the following:
       begin case declare end exception exit for goto if loop mod
       null pragma raise return select update while with
       <an identifier> <a double-quoted delimited-idPlease advise.
    Regards
    Zack

    Zack.L wrote:
    Hi Andy,
    Sorry, forgot to post the Source that's use by both AL1.1.4 and AL2.0.1.
    Source
    begin
    insert into scott.json_demo values(:title,:description);
    end;
    it's failing during the insert?
    Yes, it failed during insert using AL2.0.1.
    So the above statement produces the following error message:
    The symbol "" was ignored.
    ORA-06550: line 2, column 74:
    PLS-00103: Encountered the symbol "" when expecting one of the following:
    begin case declare end exception exit for goto if loop mod
    null pragma raise return select update while with
    <an identifier> <a double-quoted delimited-idThis suggests to me that an unprintable character (notice how there is nothing between the double quotes - "") has worked its way into your PL/SQL Handler. Note how the error is reported to be a column 74 on line 2, yet line 2 of the above block should only have 58 characters, so at a pure guess somehow there's extra whitespace on line 2, that is confusing the PL/SQL compiler, I suggest re-typing the PL/SQL handler manually and seeing if that cures the problem.

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

  • Missing keyword when try to use MERGE

    I have COUNT_STATISTICS table that needs to be updated daily.
    MODEL
    NEW_COUNT
    NEW_DATE
    OLD_COUNT
    OLD_DATE
    PRNCT_CHANGE
    XEDHRD
    5206358
    21-AUG-13
    0
    19-AUG-13
    (null)
    XLIMS
    72669230
    21-AUG-13
    72669230
    20-AUG-13
    0
    XEDHRD
    5206358
    22-AUG-13
    5206358
    21-AUG-13
    0
    XLIMS
    72859644
    22-AUG-13
    72669230
    21-AUG-13
    0.262
    so on and so forth...
    Sometimes I have a new MODEL name coming in and I have to account for that and create a row in the table in that case.
    Other times, all I have to do is INSERT new row in the table with new values.
    Simple right?
    Well, I was trying to use MERGE INTO but it is giving me problems...
    This is what I did assuming I manually went in the table and added a new MODEL name and zeros for other columns before I did insertion...
    #!/bin/bash
    MODEL=$1
    sqlplus -S username/password << EOF
    whenever sqlerror exit 1;
    set echo on
    set verify off
    INSERT INTO SEMANTIC.COUNT_STATISTICS(MODEL,NEW_COUNT,NEW_DATE,OLD_COUNT,OLD_DATE)
    SELECT MODEL,
            SELECT COUNT(*)
            FROM TABLE(SEM_MATCH(
                    ?s ?p ?o
             }',SEM_Models('$MODEL'),NULL,
            SEM_ALIASES(SEM_ALIAS('','http://VISION/DataSource/SEMANTIC#')),NULL))
        SYSDATE,
        NEW_COUNT,
        NEW_DATE
    FROM SEMANTIC.COUNT_STATISTICS
    WHERE MODEL = '$MODEL'
    AND NEW_DATE = (
                    select max(NEW_DATE)
                    from SEMANTIC.COUNT_STATISTICS
                    where MODEL = '$MODEL'
    update SEMANTIC.COUNT_STATISTICS
    set prnct_change =
       (NEW_COUNT-OLD_COUNT)/NULLIF(OLD_COUNT,0)*100
    where model = '$MODEL'
    AND NEW_DATE = (
                    select max(NEW_DATE)
                    from SEMANTIC.COUNT_STATISTICS
                    where MODEL = '$MODEL'
    COMMIT;
    exit;
    EOF
    Now I added MERGE in front of INSERT so it checks if the MODEL name doesn't exist-it creates it:
    MERGE INTO SEMANTIC.COUNT_STATISTICS s
    USING (SELECT '${MODEL}' AS MODEL, 0 AS NEW_COUNT, SYSDATE AS NEW_DATE,
      0 AS OLD_COUNT, SYSDATE AS OLD_DATE FROM dual) t
    on (s.MODEL = t.MODEL)
    when not matched then
    INSERT (s.MODEL, s.NEW_COUNT, s.NEW_DATE, s.OLD_COUNT, s.OLD_DATE)
    VALUES (t.MODEL, t.NEW_COUNT, t.NEW_DATE, t.OLD_COUNT, t.OLD_DATE);
    My code combined...
    #!/bin/bash
    MODEL=$1
      sqlplus -S username/password << EOF
      whenever sqlerror exit 1;
      set echo on
      set verify off
      MERGE INTO SEMANTIC.COUNT_STATISTICS s
      USING (SELECT '${MODEL}' AS MODEL, 0 AS NEW_COUNT, SYSDATE AS NEW_DATE, 0 AS OLD_COUNT, SYSDATE AS OLD_DATE FROM dual) t
      on (s.MODEL = t.MODEL)
      when not matched then
      INSERT (s.MODEL, s.NEW_COUNT, s.NEW_DATE, s.OLD_COUNT, s.OLD_DATE)
      VALUES (t.MODEL, t.NEW_COUNT, t.NEW_DATE, t.OLD_COUNT, t.OLD_DATE);
      exit;
    EOF
    model_exists () {
      sqlplus -s username/password <<!
        set heading off
        set feedback off
        set verify off
        set pages 0
        SELECT count(MODEL)
        FROM SEMANTIC.COUNT_STATISTICS
        where MODEL ='$MODEL' AND TO_DATE(NEW_DATE, 'DD-MON-YY') = TO_DATE(SYSDATE, 'DD-MON-YY');
        exit;
    modelcount=$(model_exists $1)
    if [ "${modelcount:-0}" -ne 0 ]; then
        sqlplus -S username/password << EOF
        whenever sqlerror exit 1;
        set echo on
        set verify off
        INSERT INTO SEMANTIC.COUNT_STATISTICS(MODEL,NEW_COUNT,NEW_DATE,OLD_COUNT,OLD_DATE)
        SELECT MODEL,
      SELECT COUNT(*)
      FROM TABLE(SEM_MATCH(
      '{?s ?p ?o }',SEM_Models('$MODEL'),NULL,
      SEM_ALIASES(SEM_ALIAS('','http://VISION/DataSource/SEMANTIC#')),NULL))
        SYSDATE,
        NEW_COUNT,
        NEW_DATE
        FROM SEMANTIC.COUNT_STATISTICS
        WHERE MODEL = '$MODEL'
        AND NEW_DATE = (
      select max(NEW_DATE)
      from SEMANTIC.COUNT_STATISTICS
      where MODEL = '$MODEL'
      COMMIT;
      exit;
    EOF
    else
       sqlplus -S  username/password << EOF
      whenever sqlerror exit 1;
      set echo on
      set verify off
      UPDATE COUNT_STATISTICS
      SET  MODEL = '$MODEL',
      NEW_COUNT = (SELECT COUNT(*) FROM TABLE(SEM_MATCH('{?s ?p ?o}',SEM_Models('$MODEL'),NULL,
      SEM_ALIASES(SEM_ALIAS('','http://VISION/DataSource/SEMANTIC#')),NULL))
      NEW_DATE  = SYSDATE,
      OLD_COUNT = NEW_COUNT,
      OLD_DATE  = NEW_DATE
      WHERE MODEL = '$MODEL'
      AND NEW_DATE = (
      select max(NEW_DATE)
      from SEMANTIC.COUNT_STATISTICS
      where MODEL = '$MODEL'
      COMMIT;
      exit;
    EOF
    fi
    sqlplus -S username/password << EOF
      whenever sqlerror exit 1;
      set echo on
      set verify off
      update COUNT_STATISTICS
      set prnct_change =
        (NEW_COUNT-OLD_COUNT)/NULLIF(OLD_COUNT,0)*100
      where model = '$MODEL'
      AND NEW_DATE = (
      select max(NEW_DATE)
      from SEMANTIC.COUNT_STATISTICS
      where MODEL = '$MODEL'
      COMMIT;
      exit;
    EOF
    But this is creating two rows if it is a new MODEL, ie:
    ./load_myScript.sh  MODELNAME
    MODEL
    NEW_COUNT
    NEW_DATE
    OLD_COUNT
    OLD_DATE
    PRNCT_CHANGE
    MODELNAME
    72669230
    22-AUG-13
    0
    22-AUG-13
    (null)
    MODELNAME
    0
    22-AUG-13
    0
    22-AUG-13
    (null)
    This is not what I want. I want to create a new row if it doesn't exist and then update that same one for that day. But tomorrow it should INSERT a new one for that same MODEL name.
    Does anyone see what I am doing wrong?

    Hi,
    MODEL is an Oracle keyword, so it causes confusion to have a column named MODEL.  Errors like "Missing Keyword" can occur when  Oracle thinks you're talking about the MODEL clause, rather than the column.
    The best solution is not to use Oracle keywords (as found in v$reserverd words) for you own column names, or other identifiers.  MODEL_NAME and MODEL_ID are good names for columns
    If you really must use that column name, qualify it with the table name, and/or put the column name in double-quotes (case-sensitive), e.g.
    count_statistics."MODEL"

  • ORA-38101: Invalid column in the INSERT VALUES Clause: "acn"

    Hi,
    Oracle version :
    Oracle Database 10g Enterprise Edition Release 10.2.0.4.0 - 64bit Production
    Funny issue,
    MERGE INTO tfc         cb1
                   USING (SELECT 5351    fs,
                                 1    cs
                          FROM   DUAL)       dual1
                        ON (cb1.fs           =    dual1.fs
                            AND cb1.asgn_cs  =    dual1.cs)
              WHEN MATCHED
              THEN
                   UPDATE
                   SET       cb1.acn          =    '145'         ,
                             cb1.cbs       =    (SELECT ta.as
                                                        FROM   tac ta
                                                        WHERE  ta.acn         = '145'
                                                        AND    ta.ent = 2),
                             cb1.bfs    =    3  ,
                             cb1.efd     =    '28-OCT-09'   ,
                             cb1.uui     =    'A'  ,
                             cb1.ut          =    sysdate
                   WHERE     cb1.fs       =    5351
                   AND       cb1.asgn_cs  =    1
              WHEN NOT MATCHED
              THEN
                   INSERT
                        (cb1.fund_cbs,
                         cb1.asgn_cs,
                         cb1.cbs,
                         cb1.fs,
                         cb1.bfs,
                         cb1.acn,
                         cb1.efd,
                         cb1.cre_usr_id,
                         cb1.uui
                   VALUES
                        (tfc.NEXTVAL,
                         dual1.cs,
                         (SELECT ta.as
                          FROM   tac ta
                          WHERE  ta.acn         = '145'
                          AND    ta.ent = 2),    
                         dual1.fs,
                         3,
                         '145',
                         '28-OCT-09',
                         'A',
                         'A'
                        );When i try to run this , get
    Error report:
    SQL Error: ORA-38101: Invalid column in the INSERT VALUES Clause: "acn"
    38101. 00000 - "Invalid column in the INSERT VALUES Clause: %s"
    *Cause:    INSERT VALUES clause refers to the destination table columns
    *Action:
    Now, when I try n remove the alias name from the insert clause, i.e.
    MERGE INTO tfc         cb1
                   USING (SELECT 5351    fs,
                                 1    cs
                          FROM   DUAL)       dual1
                        ON (cb1.fs           =    dual1.fs
                            AND cb1.asgn_cs  =    dual1.cs)
              WHEN MATCHED
              THEN
                   UPDATE
                   SET       cb1.acn          =    '145'         ,
                             cb1.cbs       =    (SELECT ta.as
                                                        FROM   tac ta
                                                        WHERE  ta.acn         = '145'
                                                        AND    ta.ent = 2),
                             cb1.bfs    =    3  ,
                             cb1.efd     =    '28-OCT-09'   ,
                             cb1.uui     =    'A'  ,
                             cb1.ut          =    sysdate
                   WHERE     cb1.fs       =    5351
                   AND       cb1.asgn_cs  =    1
              WHEN NOT MATCHED
              THEN
                   INSERT
                        (cb1.fund_cbs,
                         cb1.asgn_cs,
                         cb1.cbs,
                         cb1.fs,
                         cb1.bfs,
                         cb1.acn,
                         cb1.efd,
                         cb1.cre_usr_id,
                         cb1.uui
                   VALUES
                        (tfc.NEXTVAL,
                         dual1.cs,
                         (SELECT as
                          FROM   tac
                          WHERE  acn         = '145'  -------- remove alias from here i.e. 'ta'
                          AND   ent = 2),    
                         dual1.fs,
                         3,
                         '145',
                         '28-OCT-09',
                         'A',
                         'A'
                        );The above statement fine.
    Edited by: user8650395 on Mar 12, 2010 6:10 AM
    Edited by: user8650395 on Mar 12, 2010 6:19 AM

    Hi,
    Nice formatting!
    The first value in the INSERT clause looks suspicious:
    MERGE INTO tfc         cb1
                   INSERT
                        (cb1.fund_cbs,
                         cb1.asgn_cs,
                         cb1.cbs,
                         cb1.fs,
                         cb1.bfs,
                         cb1.acn,
                         cb1.efd,
                         cb1.cre_usr_id,
                         cb1.uui
                   VALUES
                        (tfc.NEXTVAL,     ...If tfc is a table name, then it can't be a sequnece name.
    Perhaps you meant something like
    ...            VALUES
                        (tfc_id_seq.NEXTVAL,     ...I hope that solves the problem.
    If not, post a little sample data (CREATE TABLE and INSERT statements) for the tables as they exist before the MERGE.
    Edited by: Frank Kulash on Mar 12, 2010 9:34 AM

  • Migration of million rows from remote table using merge

    I need to migrate (using merge) almost 15 million rows from a remote database table having unique index (DAY, Key) with the following data setup.
    DAY1 -- Key1 -- NKey11
    DAY1 -- Key2 -- NKey12
    DAY2 -- Key1 -- NKey21
    DAY2 -- Key2 -- NKey22
    DAY3 -- Key1 -- NKey31
    DAY3 -- Key2 -- NKey32
    In my database, I have to merge all these 15 million rows into a table having unique index (Key); no DAY in destination table.
    First, it would be executed for DAY1 and the merge command will insert following two rows. For DAY2, it would update two rows with the NKey2 (for each Key) values and so on.
    Key1 -- NKey11
    Key2 -- NKey12
    I am looking for the best possible approach. Please note that I cannot make any change at remote database.
    Right now, I am using the following one which is taking huge time for DAY2 and so on (mainly update).
    MERGE INTO destination D
      USING (SELECT /*+ DRIVING_SITE(A) */ DAY, Key, NKey
                   FROM source@dblink A WHERE DAY = v_day) S
      ON (D.Key = S.Key)
    WHEN MATCHED THEN
       UPDATE SET D.NKey = S.NKey
    WHEN NOT MATCHED THEN
       INSERT (D.Key, D.NKey) VALUES (S.Key, S.NKey)
    LOG ERRORS INTO err$_destination REJECT LIMIT UNLIMITED;Edited by: 986517 on Feb 14, 2013 3:29 PM
    Edited by: 986517 on Feb 14, 2013 3:33 PM

    MERGE INTO destination D
      USING (SELECT /*+ DRIVING_SITE(A) */ DAY, Key, NKey
                   FROM source@dblink A WHERE DAY = v_day) S
      ON (D.Key = S.Key)
    WHEN MATCHED THEN
       UPDATE SET D.NKey = S.NKey
    WHEN NOT MATCHED THEN
       INSERT (D.Key, D.NKey) VALUES (S.Key, S.NKey)
    LOG ERRORS INTO err$_destination REJECT LIMIT UNLIMITED;The first remark I have to emphasize here is that the hint /*+ DRIVING_SITE(A) */ is silently ignored because in case of insert/update/delete/merge the driving site is always the site where the insert/update/delete is done.
    http://jonathanlewis.wordpress.com/2008/12/05/distributed-dml/#more-809
    Right now, I am using the following one which is taking huge time for DAY2 and so on (mainly update).The second remark is that you've realised that your MERGE is taking time but you didn't trace it to see where time is being spent. For that you can either use the 10046 trace event or at a first step get the execution plan followed by your MERGE statement.
    LOG ERRORS INTO err$_destination REJECT LIMIT UNLIMITED;The third remark is related to the DML error logging : be aware that unique keys will empeach the DML error loggig to work correctly.
    http://hourim.wordpress.com/?s=DML+error
    And finally I advise you to look at the following blog article I wrote about enhancing an insert/select over db-link
    http://hourim.wordpress.com/?s=insert+select
    Mohamed Houri
    www.hourim.wordpress.com

  • 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

Maybe you are looking for