Database trigger to insert duplicated rows on audit table

Hi
It is possible to insert duplicate rows (at the moment database generate PK violation constraint for one specific table) within an audit table ?
Certain code like this is not working, always the whole transaction makes a rollback and audit table will be empty:
CREATE OR REPLACE TRIGGER USER.audit_TABLE_TRG
before INSERT ON USER.TABLE
REFERENCING NEW AS NEW OLD AS OLD
FOR EACH ROW
BEGIN
declare
V_conteo number(1) := 0;
duplicate_record EXCEPTION;
begin
select count(*)
into V_conteo
from USER.TABLE
where <PK conditions>
if V_conteo > 0 then
begin
INSERT INTO USER.AUDIT_TABLE
(<>)
VALUES
(<>);
raise duplicate_record;
exception
when duplicate_record then
INSERT INTO USER.AUDIT_TABLE
(<>)
VALUES
(<>);
raise_application_error(-20019,'Duplicated column1/column2:'||:NEW.column1||'/'||:NEW.column2);
when others then
dbms_output.put_line('Error ...'||sqlerrm);
end;
end if;
end;
END;
/

>
Exactly this is my problem , one only transaction (insert into audit table and try to insert into target table), the reason of this post is to know whether exists another way to insert all the intent duplicate records on target table into one audit table, you right ,maybe I can add one date column and modify the PK on audit table but my main problem still happens.
>
Can I ask you why you want to go trigger route for this if your intention is only to capture the duplicate records? Assuming that you are on at least on 10gR2, you can look at DML error table. If you go this route, there is no need for additional overhead of trigger, code failures, etc.
Oracle can automatically store the failed records in an error table which you could later on investigate and fix it or ignore it.
Simple example:
SQL> create table emp (empno number primary key, ename varchar2(10), sal number);
Table created.
SQL> insert into emp values(1010, 'Venkat', 100);
1 row created.
SQL> commit;
Commit complete.
Create error table to log the failed records
BEGIN
      DBMS_ERRLOG.create_error_log (dml_table_name => 'emp');
END;
Now let's insert a duplicate record
SQL> insert into emp values(1010, 'John', 200) ;
insert into emp values(1010, 'John', 200)
ERROR at line 1:
ORA-00001: unique constraint (VENKATB.SYS_C002813299) violated
Now use the log table to capture
SQL> insert into emp values(1010, 'John', 200) LOG ERRORS INTO err$_emp ('INSERT') REJECT LIMIT UNLIMITED;
0 rows created.
Now check the error log table and do whatever you want
SQL> r
  1* select ORA_ERR_MESG$, empno, ename, sal from err$_EMP
ORA_ERR_MESG$
EMPNO
ENAME
SAL
ORA-00001: unique constraint (VENKATB.SYS_C00
2813467) violated
1010
John
200
1 row selected.This will also capture when you do
INSERT INTO EMP SELECT * FROM EMP_STAGE LOG ERRORS INTO err$_emp ('INSERT') REJECT LIMIT UNLIMITED;
You can capture the whole record into the log table. All columns.
Regards
Edited : Code

Similar Messages

  • How to identify date & time of insertion of rows in a table

    Hi,
    Is it possible to identify the date & time of insertion of rows in a table?
    for example:
    Table name: emp
    I have rows like this
    emp_code name dept
    pr01 ram edp
    ac05 gowri civil
    pr02 sam pro
    i want to know the date and time of the insertion this( ac05 gowri civil).
    Could you please help me.....
    Thanks in advance....

    psram wrote:
    sorry for the confusion. I dont want to store date and time. I said that for example only.
    I have table which consists of thousands of rows. I want to know the insertion date & time of a particular row.
    Is it possible?So, if I have a table that stores a load of employee numbers, do you think I could get the database to tell me their names?
    If you don't store the information, you can't query the information.
    Ok, there are some dribbs and drabbs of information available from the back end of the database via the SCN's, Archive Logs etc., but those sort of things disappear or get overwritten as time goes by. The only way to know the information it to ensure you store it in the first place.
    So, in answer to your question, No, there isn't a true and reliable way to get the data/time that rows were inserted into the table, unless you have chosen to store it alongside the data.

  • Error inserting a row into a table with identity column using cfgrid on change

    I got an error on trying to insert a row into a table with identity column using cfgrid on change see below
    also i would like to use cfstoreproc instead of cfquery but which argument i need to pass and how to use it usually i use stored procedure
    update table (xxx,xxx,xxx)
    values (uu,uuu,uu)
         My component
    <!--- Edit a Media Type  --->
        <cffunction name="cfn_MediaType_Update" access="remote">
            <cfargument name="gridaction" type="string" required="yes">
            <cfargument name="gridrow" type="struct" required="yes">
            <cfargument name="gridchanged" type="struct" required="yes">
            <!--- Local variables --->
            <cfset var colname="">
            <cfset var value="">
            <!--- Process gridaction --->
            <cfswitch expression="#ARGUMENTS.gridaction#">
                <!--- Process updates --->
                <cfcase value="U">
                    <!--- Get column name and value --->
                    <cfset colname=StructKeyList(ARGUMENTS.gridchanged)>
                    <cfset value=ARGUMENTS.gridchanged[colname]>
                    <!--- Perform actual update --->
                    <cfquery datasource="#application.dsn#">
                    UPDATE SP.MediaType
                    SET #colname# = '#value#'
                    WHERE MediaTypeID = #ARGUMENTS.gridrow.MediaTypeID#
                    </cfquery>
                </cfcase>
                <!--- Process deletes --->
                <cfcase value="D">
                    <!--- Perform actual delete --->
                    <cfquery datasource="#application.dsn#">
                    update SP.MediaType
                    set Deleted=1
                    WHERE MediaTypeID = #ARGUMENTS.gridrow.MediaTypeID#
                    </cfquery>
                </cfcase>
                <cfcase value="I">
                    <!--- Get column name and value --->
                    <cfset colname=StructKeyList(ARGUMENTS.gridchanged)>
                    <cfset value=ARGUMENTS.gridchanged[colname]>
                    <!--- Perform actual update --->
                   <cfquery datasource="#application.dsn#">
                    insert into  SP.MediaType (#colname#)
                    Values ('#value#')              
                    </cfquery>
                </cfcase>
            </cfswitch>
        </cffunction>
    my table
    mediatype:
    mediatypeid primary key,identity
    mediatypename
    my code is
    <cfform method="post" name="GridExampleForm">
            <cfgrid format="html" name="grid_Tables2" pagesize="3"  selectmode="edit" width="800px" 
            delete="yes"
            insert="yes"
                  bind="cfc:sp3.testing.MediaType.cfn_MediaType_All
                                                                ({cfgridpage},{cfgridpagesize},{cfgridsortcolumn},{cfgridsortdirection})"
                  onchange="cfc:sp3.testing.MediaType.cfn_MediaType_Update({cfgridaction},
                                                {cfgridrow},
                                                {cfgridchanged})">
                <cfgridcolumn name="MediaTypeID" header="ID"  display="no"/>
                <cfgridcolumn name="MediaTypeName" header="Media Type" />
            </cfgrid>
    </cfform>
    on insert I get the following error message ajax logging error message
    http: Error invoking xxxxxxx/MediaType.cfc : Element '' is undefined in a CFML structure referenced as part of an expression.
    {"gridaction":"I","gridrow":{"MEDIATYPEID":"","MEDIATYPENAME":"uuuuuu","CFGRIDROWINDEX":4} ,"gridchanged":{}}
    Thanks

    Is this with the Travel database or another database?
    If it's another database then make sure your columns
    allow nulls. To check this in the Server Navigator, expand
    your DataSource down to the column.
    Select the column and view the Is Nullable property
    in the Property Sheet
    If still no luck, check out a tutorial, like Performing Inserts, ...
    http://developers.sun.com/prodtech/javatools/jscreator/learning/tutorials/index.jsp
    John

  • Inserting Multiple Rows in a table

    Hello,
    I need to insert multiple rows in a table with the selected items from a list (Multiple select).
    How do i go about it. I'm using ADF-struts-UIX application on Jdeveloper 9.0.5.2
    Thanks.

    Jonas, I've downloaded the sample application from your ADF UIX Editable table tip but have some problems.
    I can't even open the emp.table.uix file - errors are:
    Parsing error. Unable to parse binding.
    javax.servlet.jst.el.ELException:Function ctrl:createSortableHeaderModel was not found.
    and
    javax.servlet.jst.el.ELException:Function ctrl:getSortOrder was not found.
    Also - is there a place in the sample where you define the sample tables? They do not seem to match the standard sample emp table, for instance.
    I've just started using JDeveloper and would like to use the solution.
    Thanks - Linda

  • Insert multiple rows in on table and retreive sequence values

    Hello,
    I'm searching a way to insert several rows in a table that needs a sequence and retreive its.
    For one row i use ExecuteScalar method with the following SQL is :
    INSERT INTO MY_TABLE(MY_PK)
    VALUES(SEQ_MY_TABLE.NEXTVAL) RETURNING MY_PK INTO :MY_PARAMETER
    The aim is to insert several rows at one time. Currently I execute this SQL :
    INSERT INTO MY_TABLE(MY_PK, MY_VALUE)
    SELECT SEQ_MY_TABLE.NEXTVAL, MY_VALUE
    FROM (
    SELECT 0 MY_VALUE FROM DUAL UNION ALL
    SELECT 1 MY_VALUE FROM DUAL
    This query works well but i'm wondering how to retreive all sequence values generated by this query.
    Is it possible and how ?
    Thank you.
    Sebastien

    I tried this :
    string sql = "INSERT INTO MY_TABLE(MY_PK, MY_VALUE) " +
    "SELECT SEQ_MY_TABLE.NEXTVAL MY_PK, MY_VALUE FROM ( " +
    "SELECT 0 MY_VALUE UNION ALL " +
    "SELECT 1 MY_VALUE) " +
    "RETURNING MY_PK BULL COLLECT INTO : RETURN_IDS";
    using(var manager = myFactory.CreateDbManager()) // Initializes the connection and encapsulates ADO objects
    manager.SetCommand(sql);
    var cmd = (OracleCommand)manager.Command;
    cmd.ArrayBindCount = 2;
    var p = new OracleParameter();
    p.DbType = DbType.Int64;
    p.ParameterName = "RETURN_IDS";
    p.Direction = ParameterDirection.Output;
    p.CollectionType = OracleCollectionType.PLSQLAssociativeArray;
    p.Size = 2*sizeof (long);
    cmd.Parameters.Add(p);
    cmd.ExecuteNonQuery();
    var result = (Oracle.DataAccess.Types.OracleDecimal[])p.Value;
    But I have an error ORA-00933 that indicates that the query is wrong at "RETURNING MY_PK".
    .......................................................................................................^
    Edited by: CITnDev on 1 août 2012 13:00
    Edited by: CITnDev on 1 août 2012 15:10

  • Insert Multiple rows into the table from that table data

    Hi All,
    I have a requirement like to insert mulitple rows into the table from that table data only(I need to replicate the data).
    In this table primary key is composite primary key with all foreign keys.primary key also including the Date foreign key.I need to change that date at the of insertion.
    INSERT
    INTO myschema.Fact_page_performance
    time_sk ,
    batch_id ,
    delta_msec ,
    delta_user_msec,
    error_code_sk ,
    content_errs ,
    element_count ,
    page_bytes ,
    Available ,
    date_sk
    VALUES
    (SELECT time_sk ,
    batch_id ,
    delta_msec ,
    delta_user_msec,
    error_code_sk ,
    content_errs ,
    element_count ,
    page_bytes ,
    Available
    FROM myschema.FACT_PAGE_PERFORMANCE_BACKUP
    WHERE date_sk=20090509,20090510
    But it is giving the error like missing Expression.
    Could anyone please help to me.
    Thanks and Regards
    Swetha.

    You can have either VALUES or SELECT not both
    INSERT
    INTO myschema.Fact_page_performance
    time_sk ,
    batch_id ,
    delta_msec ,
    delta_user_msec,
    error_code_sk ,
    content_errs ,
    element_count ,
    page_bytes ,
    Available ,
    date_sk
    SELECT time_sk ,
    batch_id ,
    delta_msec ,
    delta_user_msec,
    error_code_sk ,
    content_errs ,
    element_count ,
    page_bytes ,
    Available
    FROM myschema.FACT_PAGE_PERFORMANCE_BACKUP
    WHERE date_sk=20090509,20090510;

  • Inserting multiple rows in child table

    i have two entity beans (main and child) with relationship one to many .... when i insert one row in main table (ie when i make one object for main entity bean)... how to insert multiple rows in child table...

    Can anyone pls provide some sample code for the above.. how to pass a collection and populate it in the child table.
    1.Where to pass the collection, to the childbean directly or to the parent bean and then itereate to the collectio and create child bean.
    Much obliged if you could paste some code for the above..

  • Inserting multiples rows into a table using function or procedure..

    How do i insert multiples rows into a table using function or procedure?
    Please provide me query..

    Use FORALL bulk insert statement...
    eg:
    procedure generate_test_data as
    type cl_itab is table of integer index by pls_integer;
    v_cl_itab cl_itab;
    type cl_vtab is table of varchar2(25) index by pls_integer;
    v_cl_vtab cl_vtab;
    type cl_dtab is table of date index by pls_integer;
    v_cl_dtab cl_dtab;
    begin
    for i in 1.. 100 loop
              v_cl_itab(i):= dbms_random.value(1,1000);
              v_cl_vtab (i):=dbms_random.string('a',20);
              v_cl_dtab (i):=to_date(trunc(dbms_random.value(2453737, 2454101)),'j');          
         end loop;
         forall i in v_cl_itab.first .. v_cl_itab.last
              execute immediate 'insert into test_order values( :n, :str , :dt ) ' using v_cl_itab(i), v_cl_vtab (i), v_cl_dtab (i);          
         commit;
    end;

  • Help:Oracle 9i Active database trigger for insert

    Pract 4:Active Databases
    Create a table emp1 (eno, ename, hrs, pno, super_no) and
    project (pname, pno, thrs, head_no) where
    thrs is the total hours and is the derived attribute.
    Its value is the sum of the hrs of all employees working
    on that project, eno and pno are primary keys,
    head_no is the foreign key to emp relation.
    Insert 10 tuples and write triggers to do the following
    1) Creating a trigger to insert a new employee tuple and
    display the new total hours from project table.
    2) Creating a trigger to change the hrs of
    existing employee and display the new      total hrs from project table
    3) Creating a trigger to change the project of an employee and
    display the new total hrs from project table
    4) Creating a trigger to deleting the project of an employee
    --using bom1:-
    SQL> connect hr/tiger@bom4;
    Connected.
    SQL> create table Project17
    2 (
    3 pno number(5) primary key,
    4 pname varchar2(25),
    5 thrs number(5),
    6 head_no number(5)
    7 );
    Table created.
    SQL> create table Emp17
    2 (
    3 eno number(5) primary key,
    4 ename varchar2(25),
    5 hrs number(5),
    6 pno number(5),
    7 super_no number(5),
    8 constraint Pno_fk foreign key(pno) references Project17(pno)
    9 );
    Table created.
    --Inserting records into table Emp1
    SQL> insert into Project17 values(1,'IMS',125,1);
    1 row created.
    SQL> insert into Project17 values(2,'CRM',135,1);
    1 row created.
    SQL> insert into Project17 values(3,'P and A Section',145,2);
    1 row created.
    SQL> insert into Project17 values(4,'Rishabh Dighia Steels',225,3);
    1 row created.
    SQL> insert into Project17 values(5,'BPTLibrary',215,4);
    1 row created.
    --Inserting records into table Project
    SQL> insert into Emp17 values(3,'Shubhangi',145,3,28);
    1 row created.
    SQL> insert into Emp17 values(4,'Crima',225,2,98);
    1 row created.
    SQL> insert into Emp17 values(5,'Harshada',215,4,62);
    1 row created.
    SQL> insert into Emp17 values(6,'ashish',215,4,62);
    1 row created.
    SQL> insert into Emp17 values(7,'salil',115,3,92);
    1 row created.
                        Queries:-
    connect hr/tiger@bom4;
    1) Create a trigger to insert a new emp tuple and display the new total hrs
    from project table
    create or replace trigger trigemp_ins
    after insert on Emp17
    for each row
    when(new.pno is not null)
    declare
    vthrs number(9);
    begin
    insert into Project17 values(:new.pno,pname,thrs,head_no);
    Select thrs into vthrs from Project17 where pno=:new.pno and thrs=thrs+:new.hrs;
    dbms_output.put_line('new Total Hrs:'||vthrs);
    end;
    Warning: Trigger created with compilation errors.
    SQL> show errors;
    Errors for TRIGGER TRIGEMP_INS:
    LINE/COL ERROR
    4/2 PL/SQL: SQL Statement ignored
    4/51 PL/SQL: ORA-00984: column not allowed here

    Hi,
    have a look at your insert. It misses some ":new."
    Herald ten Dam
    Superconsult.nl

  • Can not insert a row to a table from Oracle DBA Studio

    Hi,
    I try to use the Oracle DBA Studio to create a table and put some test data in it. Here is what I found:
    I start Oracle DBA Studio on the client machine by connecting to an Oracle server 8i (8.1.7). I create a simple table called Test with two columns: one is USER, VARCHAR2, 10; and the other is USER2, CHAR, 2. After that, I right click on the table name and select "Table Data Editor" from the popup menu. The table editor window shows up. I type in the value 'AA' and 'BB' in the grid of two columns. Then I click the Apply button. An error message box popped up:
    ORA-00928 missing SELECT keyword.
    I click Show SQL button. The SQL statement is as following:
    INSERT INTO "TASYS"."TEST" (USER ,USER2 ) VALUES ('AA' ,'BB').
    I copy the statement to SQL Plus and run it. The same error is generated. But if I remove (USER, USER2) from the statement, it inserts a row without complaint. In other word, the database will not allow to insert if individual columns are list. I realize something must wrong with the new server and client installed and could not figure out what happening. Hope someone can help.
    Thanks.
    null

    I am not sure, but could it be that USER is a keyword or predefine word. Check Oracle'slist of predefine/keyword

  • Insert multiple rows in a table

    Hello Apex expert,
    I need help on insert multiple rows. it may look easy but I don't know how to do it.
    I have a table (with name found_table) which has these fields: found_ item_id, item_name, current_location, cost_center, tag_number. Also, I have a table (with the name transition) which has these fields: transition_id, found_item_id (FK to found_table), from_location, to_location, From_cost_center, to_cost_center, tag_number.
    I have an interactive report on found_table which I would like to add checkbox to all rows of the report. When the user checks any rows and press submit, I would like to send all these selected rows to another page which I have a form on transition table. The user will select a to_location and to_cost_center from this page (by the way from_location and from_cost_center and tag_number is the same as current_location and cost_center, tag_nuber from found_table, which I figured it out how to show those as a default in the new form). Now I want when a user selects the new location and cost center and press submit, all those selected rows be inserted in transition table with new locations.
    I read several threads on forum, but I could not find a solution for my problem. I will appreciate your help.
    Thanks,
    Atousa

    Hello again,
    I created a report with check box. I also added two selected list at the top of the region to select the location and cost center. Also, there is a transfer button(as submit) to insert the new data to table. Now I need the insert process. I tried different insert process but none of them is working for me:(((
    I created an example of what I need to do in the apex that you can take a look and give me some advise. The link is:
    What I need to do is:
    When a user selects several rows by using checkbox and selects To_LOCATION, and TO_COST_CENTER from selected list, and clicks on transfer, all the data should be insert in to another table with the name transition as follows:
    from found table to transition table
    found_item_id(pk) found_item_id (fk)
    current_location from_location
    cost_center from_cost_center
    tag_number tag_number
    selected list (to_location) to_location
    selected list (to_cost_center) to_cost_center
    Please help me on that. I appreciated.
    Atousa
    Edited by: Atousa.M on Jul 21, 2011 10:55 AM

  • Insert new row in Data Table

    Hi All,
    Based on "Insert, Update and Delete" tutorial it's easy to perform insert by addidng new row in forms.
    Then I tried to do the myRowSet.moveToInsertRow() having a the RowSet bound to a Data Table and no new record appears :( !
    Any workaround ?

    My guess is that you are not refreshing the datatable - you must call execute on the datatable model object again.
    Unless you are expecting a new "inserted" empty row to be created on the datatable itself when you call moveToInsertRow - the JSF standard datatable doesn't support that operation. See the AppModel sample application to see another option to handle that scenario.
    v

  • Inserting multiple rows in a table automatically

    Hello everyone,
    A question about SQL/PLSQL.
    I have a homework to create a table in SQL and to insert 10,000 rows in the table regardless of what the values are. The question is: is there a way (like a PLSQL code that has a loop) to inserts values in a table automatically without the need to insert the values 10,000 times manually?
    I really appreciate it and thanks in advance...

    Frank Kulash wrote:
    Is it possible to give me an example of a complete Connect BY/Insert statement would look like in my case?See the SQL Language reference manual
    http://download.oracle.com/docs/cd/B28359_01/server.111/b28286/statements_9014.htm#i2145081
    or your textbook for examples of inserting values with a subquery.
    A subquery using dual will work as well as a subquery using any other table; there's nothing about dual or CONNECT BY that complicates using a subquery in an INSERT statement.
    If you get stuck, post your best attempt here. If your problem involves an error, then post the complete error message, too.Frank,
    Thank you for your help and reply.
    I think I did not explain the situation well because what I am looking for is called <b>populating a table</b> and it seems that the CONNECT BY makes a loop of a single column and that is not the case.
    I have a table which is called customer and it contains 7 coulmns in which the first one (cust_id) is sequenced as shown below:
    create table customers
    cust_id int primary key,
    f_name varchar2(40),
    l_name varchar2(40),
    address varchar2(40),
    postnr varchar2(40),
    city varchar2(40),
    e_mail varchar2 (40)
    create sequence cust_id
    minvalue 0
    maxvalue 99999
    start with 1
    increment by 1
    cache 20;Now the quesiton is: how to populate this table with random data of 10,000 rows?
    Thank you very much in advanced.

  • Query to insert a row in a table with same values except 1 field.

    Suppose I have a table with 100 columns(fields).
    I want to insert a row with 99 fileds being the same as previous ones except one fileld being different.
    The table doesn't have any constraints.
    Kindly suggest a query to solve the above purpose..

    And for much more lazy people, a desc of table is shorter to write. :-)
    Then copy & paste into any editor, then mode column to add a comma after every column name in one shot.Or have the system do it for you. Be lazy.
    SELECT Column_Name || ',' FROM User_Tab_Columns where Table_Name = '';
    Indeed, it can be converted to a script called desc(.sql)
    SELECT Column_Name || ',' FROM User_Tab_Columns where Table_Name = '&1' ORDER BY Column_Id;
    Then desc or @desc.

  • Inserting multiple rows into a table using a multiple-select list

    I'm trying to figure out how to take the output of a multiple-select list (":" separated list of values) and use that to update a table by inserting multiple rows based on the values. Is there a straight-forward way to do that in APEX?
    Thanks.
    Chris

    Hi Chris,
    I think this should give you what you need: Working with a Multiple Select List Item
    --Jennifer                                                                                                                                                                                                                                                                                                                                                                                                   

Maybe you are looking for

  • How do I view mov files in my iPad2

    I have taken some hd videos and have some mov files that I want to view on my iPad2. I downloaded the files in my ipad2 and the file shows as a mov file but I can not open them. What is the best option to view these files in the ipad2.

  • How to transfer photos from ipad to new itunes

    Hi, Iam having a question. I had an ipad with 3g. lots of datas we stored thru itunes from our laptop. unfortunately our laptop was corrupted and we lost all our datas incl. itunes. we lost all photos in the laptop. the only datas we had is in the ip

  • SQ01 Query on VBRK billing docs

    Hi Experts I have a issue where we ran an customised query for the return billing documents the value for the return items is not showing the negative value in the report , Pls help me to know how does the Query report the billing values shows, Pleas

  • Setting for e-print.

    On my wireless officejet 4500 g 510 control panel It does not have any setting for me to print the email address, Im not to sure that I am even doing any right. Hopefully, I haven't messed anything up.

  • Bom billing plan

    PLEASE TELL ME STEP BY STEP PROCESS OF CONFIGURING MILE STONENBILLING IN CASE OF  BOM ITEMS