Before delete trigger and foreign key relationship

Hi,
I am analysing one database for migration. On one parent table there is before delete trigger , to delete records from child. Also there is foreign key relationship on child table for this parent table.
When I am deleting a row from parent, message gets displayed as "there are child records found."
I would like to know, if there is foreign key relatioship then delete trigger on parent does't work, what is exactly happening?

Could you post that trigger code and the Oracle version as well?
With basic assumptions, I can't reproduce what you have stated here.
Connected to:
Oracle Database 10g Enterprise Edition Release 10.2.0.4.0 - Production
With the Partitioning, OLAP, Data Mining and Real Application Testing options
SQL> create table parent (id number primary key);
Table created.
SQL> create table child (id number);
Table created.
SQL> alter table child add constraint fk_parent foreign key (id) references parent;
Table altered.
SQL> create or replace trigger bdr_parent
  2  before delete on parent
  3  for each row
  4  begin
  5  delete from child where id = :old.id;
  6  end;
  7  /
Trigger created.
SQL> insert into parent (id) values (1);
1 row created.
SQL> insert into child (id) values (1);
1 row created.
SQL> commit;
Commit complete.
SQL> delete from parent where id = 1;
1 row deleted.
SQL> select * from parent;
no rows selected
SQL> select * from child;
no rows selected
SQL> rollback;
Rollback complete.
SQL> alter table child drop constraint fk_parent;
Table altered.
SQL> alter table child add constraint fk_parent foreign key (id) references parent on delete cascade;
Table altered.
SQL> delete from parent where id = 1;
delete from parent where id = 1
ERROR at line 1:
ORA-04091: table SCOTT.CHILD is mutating, trigger/function may not see it
ORA-06512: at "SCOTT.BDR_PARENT", line 2
ORA-04088: error during execution of trigger 'SCOTT.BDR_PARENT'
SQL>

Similar Messages

  • Mapping in OWB with primary key and foreign key relationship

    Hi all,
    I am new to this datawarehousing field. I have just started my career. I have to now create a mapping in owb where a table has a field which is a primary key of another table in the same staging area. If you guys could help me out with the a method it can be created that would be very helpful to me.
    I thought of 2 ideas,
    1. If I can use a look up, but then I am not sure if i can use a lookup for primary key, foreign key relationship. If I can use also, I do not know how to use that.
    2. What if I can directly take that the first table and link the primary key of that table to the second table which uses that primary key of the first table as one of its fields.
    I do not know how feasible these methods are. Please guys help me out.
    Thanks in advance.

    I have a similar case where table a and table b having relation but table a got inserted with data and table b is empty so there no values for foriegn key column in table b to realte with table a.
    Now i want to load table b foriegn key with primary key column values of table a.
    how can we do this in owb
    thanks
    kumar

  • Lack of Primary and Foreign Keys and Efficiency

    I am reverse engineering a Maximo database. I am shock that it does not have Primary or foreign keys define for 590 out of 620 tables.
    My question is does the lack of Primary and Foreign key relationships adversely impact the efficiency of an Oracle database? I think it does IBM techs do not think it does.
    Anyone has the answer?

    does the lack of Primary and Foreign key relationships adversely impact the efficiency of an Oracle database? Not necessarily. There are many large OLTP databases that do not define PKs and FKs.
    It is true that the presence of constraint defintions is used by the optimizer. However,
    what matters is how the application is written and how the optimizer handles it.
    Remember that Oracle Databases have been in production since before constraint definitions were introduced.
    Hemant K Chitale
    Edited by: Hemant K Chitale on Jun 9, 2010 10:05 AM

  • Problem with Foreign Key relationships in SAP R/3 4.7

    Hi Experts,
    I am trying to create a foreign key relationship between 2 transparent tables in SAP R/3 4.7
    Table 1:ZAAVNDR (MANDT (pk), VENDORNO (pk), NAME, REGION, COUNTRY (fk)) Foreign Key Table
    Table 2: ZAAVNDRREF(MANDT(pk), COUNTRY (pk)) ---Check table
    I have added few valid countries in check table but when I am adding some records in foreign key table with invalid countries these records are not being restricted and are still successfully going into the table.
    Could any one please help in this.
    Thanks in anticipation.
    -Amit

    Hi Sandra,
    Many thanks for your response and providing time of yours.
    Now, I have done exactly the same thing, but still it is the same.
    I have created two new tables as below:
    ZAAVREF (Check table)
    MANDT (PK)
    COUNTRY (PK) Domain:ZAACOUNT (CHAR 10)
    ZAAV1 (Foreign key table)
    MANDT (PK)
    COUNTRY (PK) Domain:ZAACOUNT (CHAR 10)
    Then I have created FK on country of foreign key table ZAAV1 and then SE16 (for table ZAAVREF)->Create Entries-> Entered values for Country only->Save....Records entered with valid Country values.
    After that SE16 (for table ZAAV1)->Create Entries-->Entered an Invalid country->Save->Still the record entered to the Database successfully....
    Could you please let me know where I am going wrong.
    I am using SAP R/3 4.7 and creating tables using Tools->ABAP Workbench->Development->ABAP dictionary

  • Get Current SQL in Before delete trigger

    Hi,
    I have created a before delete trigger to track which records are deleted from a table I need to know what statements fires the trigger. can someone please describe how I can retrieve the current SQL.
    using sys_context('userenv','CURRENT_SQL') returns null for CURRENT SQL
    Note:
    For me the easier is to enable auditing and audit delete on the table however at the moment I cant get a downtime from the business to bounce the database to enable auditing.
    CREATE OR REPLACE TRIGGER before_delete BEFORE DELETE
    ON AUDIT_TEST_TAB
    FOR EACH ROW
    DECLARE
    v_username varchar2(50);
    v_stmt varchar2(255);
    v_client_info varchar2(200);
    v_os_user varchar2(50);
    v_machine varchar2(50);
    v_program varchar2(50);
    v_module varchar2(50);
    v_auth_type varchar2(200);
    v_ip_addr varchar2(200);
    v_sql_statement VARCHAR2(4000);
    BEGIN
    SELECT sys_context ('USERENV', 'CURRENT_SQL')
    INTO v_sql_statement
    FROM dual;
    -----------insert into logging table statment ----
    end;

    A few comments.
    Lets assume you run a delete statement that deletes 550 rows from your table. If your trigger is working then the very same statement would be stored 550 times. I think an BEFORE or better an AFTER delete STATEMENT level trigger would be the better choice. Why AFTER? Because if the delete operation fails, for example because of existing child records, then everything is rolled back anyway to the implicit savepoint just before the delete.
    So to store the SQL statement the correct trigger would be an AFTER STATEMENT DELETE trigger.
    Now what to store: You want the sql statement. You could try to find the cursor/currently running SQL. It might be tricky to separate that from the SQLs that you run to find this out.
    It could even be possible to simply save all commands that are in your PGA/Cached cursor area. First find out yur session, then store the SQL_text (first 60 chars) for all the cursors in this session by using v$open_cursor or the first 1000 chars by using v$sql.
    Here are a few views that might be helpful. v$session , v$open_cursor, v$sql, v$sqltext, v$sql_bind_data, v$sql_bind_capture, dba_hist_sqltext

  • Maintenance View for custom table with foreign key relationship

    Hi Folks,
         I have created a custom table with foreign key relationship with other check tables. I want to create a maintenance view / tablemaintenance generator. What all things I need to take care for the foreign keys related fields while creating the maintenance view / tablemaintenance generator.
    Regards,
      santosh

    Hi,
    You do not have to do anything explicitely for the foreign key relationships in the table maintainance generator.
    Create the table maintainance generator via SE11 and it will take care of all teh foreign key checks by itself.
    Regards,
    Ankur Parab

  • Code generation - foreign key relationships

    I'm using the code/descriptor generation tab to generate classes from existing tables. It offers an option of choosing which relationships to generate, but seems to miss out some of the defined foreign key relationships in the database.
    I have three tables, CLIENTS, TXNS and REG
    The following constraints are defined in my database:
    TXN Primary Key: (TXN_ID)
    CLIENTS Primary Key :CLIENT_ID, TXN_ID)
    CLIENTS Foriegn KEy : TXN_ID references TXNS
    REG Primary Key: CLIENT_ID, TXN_ID
    REG Foreign Key: CLIENT_ID, TXN_ID references CLIENTS
    I select these three tables and choose generate classes and descriptors for selected tables. When the "Choose Relationships to generate" screen comes up, it only shows me the CLIENTS<-->TXNS relationship, but not the REG<-->CLIENTS relationship, even though the database foreign key constraints all look as though they've been defined in similar ways.
    thanks for any help.

    Hi Matt,
    I'm not surprised that you have an issue with this. One bugbear I have with Gateway is that for some reason the designers don't think any context beyond the immediate preceding navigation node is important. They don't support this within the same service,so it's hardly likley to work in a service reference.
    I may be wrong but I don't think GW is OData compliant in this respect. If I have the navigation path /blindservice/FromHereSet(1)/ToAPoints(22)/ToBPoints, it's rather restrictive to say I cannot see the initial key of '1' in the path when I am trying to resolve 'ToBPoints'. If that value - where I started - is key to the context, I have to know it.
    Currently the only way to access this context is to embed the 'key history' in the intermediate entities, i.e. /blindservice/FromHereSet(1)/ToAPoints(1,22)/ToBPoints. In my view that is corrupting the URl to suit the limitations of the SAP OData implementation. What's even more confusing/frustrating is that the technical request context appears to be able to store the stacked navigation keys but doesn't make use of this design. 
    I feel your pain
    Ron.

  • Primary key and Foreign key on same column

    Hi, I am able to create below tables , primary and foreign keys as below.
    But Is this valid design? Can I define a column (ckey2 in table "child") as
    primary key and as well as foreign key?
    CREATE TABLE parent (
    col1 NUMBER,
    col2 NUMBER
    CREATE TABLE child (
    ckey1 NUMBER,
    ckey2 NUMBER,
    ckey3 NUMBER
    alter table parent add constraint parent_pk primary key( col1 );
    alter table child add constraint child_pk primary key( ckey2 );
    alter table child add constraint child_fk foreign key( ckey2 ) references parent( col1);
    Thanks.

    Can I define a column (ckey2 in table "child") as primary key and as well as foreign key?You mean you want to define a one-to-one relationship between parent and child tables.. why would you want to do that ? You might as well merge the 2 tables into one.

  • How to make before delete trigger

    Hi all
    I want make before delete trigger
    I have 2 tables hr_api_transactions and new_table
    when I delete records from hr_api_transations table
    then that deleted record should be stored/insert in new_table table
    for that purpose I need before delete trigger
    How can I make It?

    Hi
    I have written following code but it gives an error
    CREATE OR REPLACE TRIGGER before_delete_trigger
        BEFORE DELETE
            ON HR_API_TRANSACTIONS
            FOR EACH ROW
        DECLARE
        BEGIN
            delete from new_table where new_table.name = OLD.hr_api_transactions.api_addtnl_info;
        END;
    TRIGGER BEFORE_DELETE_TRIGGER compiled
    Errors: check compiler logafter show errors it shows
    4/54 PL/SQL: ORA-00904: "OLD"."HR_API_TRANSACTIONS"."API_ADDTNL_INFO": invalid identifier
    4/9 PL/SQL: SQL Statement ignoredhere hr_api_transaction is table which contain API_ADDTNL_INFO column
    and name column of new_table and API_ADDTNL_INFO column of
    HR_API_TRANSACTIONS table are same

  • Lost about 60-75% of my primary and foreign keys when Migrating from SQL Server 7

    Hi All,
    I did an almost successful migration between SQL Server 7.0 and Oracle9i.
    What happened:
    I seem to have lost my primary and foreign keys in the migration. The funny thing is when I viewed the constraints and indexes in Toad, they were there. However when I tried to enabled those constraints nothing happened.
    I really don't know how I can fixed this, but I don't understand why I didn't get a warning or an error message in the Migration Workbench (latest version).
    I did ignore the following errors, could that have anything to do with the keys being lost.
    Failed to create User:omwb_emulation; ORA-1920: user name "OMWB_EMULATION" conflicts with another user or role name
    Failed to create User:guest;ORA-01920: user name "GUEST" conflicts with another user or role name
    These users do not own any objects therefore I ignored them.
    Please advise
    Thanks

    Hi Joe,
    Not sure why you are able to see these objects and yet not able to enable them. Did you encounter any errors during the create Oracle Model phase?? Did you encounter any errors during the final Migrate phase?
    Also, it is really important to have a tablespace created before an attempt is made to create tables and indexes in the destination Oracle database.
    Regards
    John

  • Primary Key and Foreign Key Constraints

    Hi All,
    I would like to know PRIMARY KEY and FOREIGN KEY constraints on existing oracle tables. Could any one suggest me how to find out.
    Thanks,
    RED

    You can query DBA_CONSTRAINTS to get a list of all the constraints on table A and/or table B. The documentation I linked to gives a full list of the data you can see in DBA_CONSTRAINTS, but it includes things like the referenced table name and referenced constraint name for a foreign key constraint. If A is a parent of B or B is a parent of A, you could match up the parent's primary key constraint to the child's foreign key constraint.
    More generally, though, if you don't know that one of the tables is a parent of the other, figuring out how to join the two tables is probably not something that can be done using just the Oracle data dictionary. You would probably need an understanding of the data model being used to figure out what intermediate table(s) needed to be joined in order to relate rows in A to rows in B.
    Justin

  • How to transfer database table contain null values, primary key, and foreign key to the another database in same server. using INSERT method.

    how to transfer database table contain null values, primary key, and foreign key to the another database in same server. using INSERT method.  thanks

    INSERT targetdb.dbo.tbl (col1, col2, col3, ...)
       SELECT col1, col2, col3, ...
       FROM   sourcedb.dbo.tbl
    Or what is your question really about? Since you talke about foreign keys etc, I suspect that you want to transfer the entire table definition, but you cannot do that with an INSERT statement.
    Erland Sommarskog, SQL Server MVP, [email protected]

  • Primary and Foreign Keys

    I've attempted to identify a primary and foreign key in these two tables, but I am getting a bunch of errors re duplicate keys and column names needing to be unique. Can someone explain to me what I am doing wrong? I have watched numerous tutorials. Perhaps
    the primary and foreign key I have identified don't meet the criteria?
    CREATE TABLE StockNames
    -- Added Primary key to [stock_symbol]
    [stock_symbol] VARCHAR(5) NOT NULL CONSTRAINT PK_stock_symbol PRIMARY KEY,
    [stock_name] VARCHAR(150) NOT NULL,
    [stock_exchange] VARCHAR(50) NOT NULL,
    GO
    stock_symbol stock_name stock_exchange
    AEA American External Accessories NYSE
    ASP All Sports Portal NYSE
    AIT Anthony Interest Technology NYSE
    ATV American Technology Vehicles NYSE
    ACM Anderson Charles and Mitchell NYSE
    ACH American Career Helpers NYSE
    AVA Alleviate America NYSE
    and the second table
    CREATE TABLE DailyPricesA (
    [stock_symbol] VARCHAR (5) NOT NULL CONSTRAINT FK_stocksymbol REFERENCES [StockNames]([stock_symbol]),
    [date] VARCHAR (15) NOT NULL,
    [stock_price_open] FLOAT (53) NOT NULL,
    [stock_price_high] FLOAT (53) NOT NULL,
    [stock_price_low] FLOAT (53) NOT NULL,
    [stock_price_close] FLOAT (53) NOT NULL,
    [stock_volume] INT NOT NULL,
    [stock_price_adj_close] FLOAT (53) NOT NULL,
    stock_exchange stock_symbol date stock_price_open stock_price_high stock_price_low stock_price_close stock_volume stock_price_adj_close
    NYSE AEA 8/02/2010 4.42 4.42 4.21 4.24 205500 4.24
    NYSE AEA 5/02/2010 4.42 4.54 4.22 4.41 194300 4.41
    NYSE AEA 4/02/2010 4.55 4.69 4.39 4.42 233800 4.42

    Hi Stan,
    I have removed "stock_exchange" - that removed that error. These are the other errors I am experiencing:Msg
    2714, Level 16, State 6, Line 8
    There is already an object named 'DailyPricesA' in the database.
    Msg 2714, Level 16, State 6, Line 36
    There is already an object named 'StockNames' in the database.
    Msg 2627, Level 14, State 1, Line 47
    Violation of PRIMARY KEY constraint 'PK__StockNam__117C59C768B2BB7F'. Cannot insert duplicate key in object 'dbo.StockNames'. The duplicate key value is (AA).
    The statement has been terminated.
    Msg 1913, Level 16, State 1, Line 54
    The operation failed because an index or statistics with name 'SNIndex' already exists on table 'DailyPricesA'.
    And the code:
    USE NYSEDatabaseProject
    -- Drop the table to clean up database.
    --DROP TABLE DailyPricesA
    --GO
    -- Create the table.
    CREATE TABLE DailyPricesA (
    [stock_symbol] VARCHAR (5) NOT NULL CONSTRAINT FK_stocksymbol REFERENCES [StockNames]([stock_symbol]),
    [date] VARCHAR (15) NOT NULL,
    [stock_price_open] FLOAT (53) NOT NULL,
    [stock_price_high] FLOAT (53) NOT NULL,
    [stock_price_low] FLOAT (53) NOT NULL,
    [stock_price_close] FLOAT (53) NOT NULL,
    [stock_volume] INT NOT NULL,
    [stock_price_adj_close] FLOAT (53) NOT NULL,
    -- Add a foreign key.
    -- [stock_symbol] VARCHAR (5) NOT NULL CONSTRAINT FK_stocksymbol REFERENCES [StockNames]([stock_symbol]),
    BULK INSERT DailyPricesA
    from 'C:\Users\fenwky\NYSE_daily_prices_A.csv'
    -- firstrow = 2 skips the header row, field terminator =',' deterines the separator, and rowterminator defines where the row ends
    with (firstrow = 2, fieldterminator = ',', rowterminator = '\n')
    GO
    -- Create an index named DPAIndex, for the columns stock_symbol//'DPAIndex' already exists on table 'DailyPricesA'
    --CREATE INDEX DPAIndex
    --ON DailyPricesA (stock_symbol);
    -- Drop the table to clean up database.
    -- DROP TABLE StockNames
    -- GO
    CREATE TABLE StockNames
    -- Added Primary key to [stock_symbol]
    [stock_symbol] VARCHAR(5) NOT NULL CONSTRAINT PK_stock_symbol PRIMARY KEY,
    [stock_name] VARCHAR(150) NOT NULL,
    [stock_exchange] VARCHAR(50) NOT NULL,
    GO
    -- Insert the CSV into the table named Stocknames
    BULK INSERT StockNames
    from 'C:\Users\fenwky\NYSE_stock_names.csv'
    -- firstrow = 2 skips the header row, field terminator =',' deterines the separator, and rowterminator defines where the row ends
    with (firstrow = 2, fieldterminator = ',', rowterminator = '\n')
    GO
    -- Create an index named SNIndex, for the columns stock_symbol and stock_exchange.
    CREATE INDEX SNIndex
    ON DailyPricesA (stock_symbol);
    -- Select all from DailyPricesA
    select * from StockNames

  • How to create a Foreign key relationship between 2 user defined tables...

    Hi Folks,
    I have created two user defined tables... Where in i want to create foriegn key relationship between the 2 tables.... Can anyone guide the step by step procedure to do this scenario...
    Any help would be highly appreciated...
    Thanks

    Hi
    1.  In the 2nd table call the field of the 1st table which is a primary key.
    2.  Give the same field and dataelement name.
    3.  Select that field and then click on the foreign key field icon which is beside Search Help button.
    4. Then give short text, and the 1st table name.
    5. Then in the below box give the 2nd table name and 2nd table field name which you have called from 1st table.
    6. Then click on copy, then u will be able to see Check table name and check table field name beside foreign key table name.
    7. Then again click on copy.
    Regards
    Haritha.

  • Composite Foreign Key Relationships

    I'm having problems defining relationships that are using the same set of fields in a composite primary key and a composite foreign key. Are there any examples for doing this kind of thing. I think I have the primary keys set up correctly but the foreign key defs aren't working yet. From the spec it looks ike it should be something like this:
    @ManyToOne
         @PrimaryKeyJoinColumns({
         @PrimaryKeyJoinColumn(name="CGMTI_ID"),
         @PrimaryKeyJoinColumn(name="MISSION_REF_DATE")})
         CgmtiHeader cgmtiHeader;
    Also, the composite foreign keys seem to make Dali's entity generation blow up.

    This mapping is missing the referencedcolumn definition, and because it is a composite pk, it cannot figure out a default value. So it should similar to:
    @ManyToOne
    @PrimaryKeyJoinColumns({
    @PrimaryKeyJoinColumn(name="CGMTI_ID", referencedColumnName="CGMTI_ID),
    @PrimaryKeyJoinColumn(name="MISSION_REF_DATE", referencedColumnName="MISSION_REF_DATE)})
    CgmtiHeader cgmtiHeader;
    Similar discussions exist in threads:
    Extra Columns in ManyToMany table workaround
    and
    http://forums.java.net/jive/thread.jspa?threadID=2564&messageID=36441
    both of which list blogs showing examples.
    Best Regards,
    Chris

Maybe you are looking for