Create foreign keys to delete child records

I am unfamiliar with foreign keys, I have 3 tables one is the parent table if a record is deleted in the parent table I would like the record to be deleted from the child record but I think that I am also confused about which should be the parent table
(purpose is to use in a form)
parent table (i think)
AdminEntry table
entryid ,
date1,
date1desc,
date2,
date2desc,
date3,
date3desc
In a form each date and its description is placed in the following table
CalendarEntry table
calendarid,
date,
datedesc
entryid (fk)?
so CalendarEntry will have many entries at least 3 from one entryId, this I get but what if I want to delete lets say date2 and date2desc record. If I delete it from AdminEntry table how will calendarEntry table know which one to delete?
Please help very confused.
(the other table also inserts to the CalendarEntry table)

There is a demo of this functionality in Morgan's Library at www.psoug.org under Foreign Keys.
Look for ON DELETE CASCADE.

Similar Messages

  • Delete child record

    hi is there a quikestt way i can delete child record of the parent table,lets say i have 100 record in child record related to one parent how can i delete the 100 record in smart way not by deleting one by one vale

    You coluld find it easily by googling..
    create table test_dept(dept_id number primary key,dep_name varchar2(50));
    create table test_emp(emp_id number primary key,
          dept_id number references test_dept on delete cascade,emp_name varchar2(50));

  • Unable to create foreign key: InvalidArgument=Value of '0' is not valid for 'index'. Parameter name: index

    I am running an SQL(CE) script to create a DB. All script commands succeed, but the DB get "broken" after creating the last costaint: after running the script, viewing table properties of Table2 and clicking on "Manage relations" gives the following error: Unable to create foreign key: InvalidArgument=Value of '0' is not valid for 'index'. Parameter name: index. Wondering what does that refer to...
    Here it is the script. Please note that no error is thrown by running the following queries (even from code that passing the queries by hand, one-by-one to sql server management studio).
    CREATE TABLE [table1] (
    [id_rubrica] numeric(18,0) NOT NULL
    , [id_campo] numeric(18,0) NOT NULL
    , [nome] nvarchar(100) NOT NULL
    GO
    ALTER TABLE [table1] ADD PRIMARY KEY ([id_rubrica],[id_campo]);
    GO
    CREATE UNIQUE INDEX [UQ__m_campi] ON [table1] ([id_campo] Asc);
    GO
    CREATE TABLE [table2] (
    [id_campo] numeric(18,0) NOT NULL
    , [valore] nvarchar(4000) NOT NULL
    GO
    ALTER TABLE [table2] ADD PRIMARY KEY ([id_campo],[valore]);
    GO
    ALTER TABLE [table2] ADD CONSTRAINT [campo_valoriFissi] FOREIGN KEY ([id_campo]) REFERENCES [table1]([id_campo]);
    GO
    Sid (MCP - http://www.sugata.eu)

    I know this is kind of old post, but did this realy solved your problem?
    I'm getting this same error message after adding a FK constraint via UI on VS2008 Server Explorer.
    I can add the constraint with no errors, but the constraint is not created on the DataSet wizard (strongly typed datasets on Win CE 6) and when I click "Manage Relations" on the "Table Properties" this error pop out:
    "InvalidArgument=Value or '0' is not valid for 'index'.
    Parameter name: index"
    Even after vreating my table with the relation in SQL the same occurs:
    CREATE TABLE pedidosRastreios (
        idPedidoRastreio INT NOT NULL IDENTITY PRIMARY KEY,
        idPedido INT NOT NULL CONSTRAINT FK_pedidosRastreios_pedidos REFERENCES pedidos(idPedido) ON DELETE CASCADE,
        codigo NVARCHAR(20) NOT NULL

  • How to create foreign key automatically?

    I am writing to seek help, in regards creating foreign key automatically, when I insert data into my ''price'' table.  I have 2 tables, one called prices and names.  the relationship between them, if that one name can have many prices and one price
    can have many names (many-to-many). Hence, i have junction table called  "Name_Prices", as shown below in the sample database schema:
    Names
    name_id [pk]
    name
    type
    UploadDate
    Prices
    Price_id [pk]
    name_id [fk]
    price
    uploadDate
    Name_Prices
    name_id REFERENCE names (name_id)
    price_id REFERENCE prices (price_id)
    PRIMARY KEY (name_id, price_id)
    The  price's data input comes in as CSV file everyday. (please see the example below) :
    name name_type price UploadDate
    ALBA MBS 93.5 17/10/2014
    ALESC Trup 58 17/10/2014
    ALESC Trup 52 17/10/2014
    My desire goal/output is to be able to create a functionality, where I can insert the price's data into the database (''prices''), it will automatically insert foreign key in the price
    table (from the names table), and if there is a new price's name, then the database will create a new name id for it, in the name's table, transferring the name, its type, from the CSV input data. 
    In order to achieve this task, where would I start implementing this logic?(in SQL server or application-side) what steps does this involve and is this task achievable, all in sql server side (i.e. store procedure, functions etc..). 
    Apology in advance, if the question is not clear to understand, i happy to follow up with further questions, if required.  
    Any help would be very appreciated. Many thanks

    As noted above, I modified the design:
    Products
    Product_id [pk]
    Product
    type
    UploadDate
    Prices
    Price_id [pk]
    price
    uploadDate
    Product_Prices
    Product_id REFERENCE Products (Product_id)
    price_id REFERENCE prices (price_id)
    PRIMARY KEY (Product_id, price_id)
    Note
    Kalman Toth Database & OLAP Architect
    SQL Server 2014 Database Design
    New Book / Kindle: Beginner Database Design & SQL Programming Using Microsoft SQL Server 2014

  • Is it possible to create foreign key from composite key in other table.

    SQL> desc PRODUCT_CONFIG_OPTION;
    Name Null? Type
    CONFIG_ITEM_ID NOT NULL VARCHAR2(20) --composite primary key
    CONFIG_OPTION_ID NOT NULL VARCHAR2(20) --composite primary key
    CONFIG_OPTION_NAME VARCHAR2(100)
    DESCRIPTION VARCHAR2(255)
    SEQUENCE_NUM NUMBER(18)
    LAST_UPDATED_STAMP TIMESTAMP(6)
    LAST_UPDATED_TX_STAMP TIMESTAMP(6)
    CREATED_STAMP TIMESTAMP(6)
    CREATED_TX_STAMP TIMESTAMP(6)
    SQL> DESC PRODUCT_CONFIG_ITEM;
    Name Null? Type
    CONFIG_ITEM_ID NOT NULL VARCHAR2(20)
    CONFIG_ITEM_TYPE_ID VARCHAR2(20)
    CONFIG_ITEM_NAME VARCHAR2(100)
    DESCRIPTION VARCHAR2(255)
    LONG_DESCRIPTION CLOB
    IMAGE_URL VARCHAR2(255)
    LAST_UPDATED_STAMP TIMESTAMP(6)
    LAST_UPDATED_TX_STAMP TIMESTAMP(6)
    CREATED_STAMP TIMESTAMP(6)
    CREATED_TX_STAMP TIMESTAMP(6)
    SQL> desc product;
    Name Null? Type
    PRODUCT_ID NOT NULL VARCHAR2(20)
    PRODUCT_TYPE_ID VARCHAR2(20)
    PRIMARY_PRODUCT_CATEGORY_ID VARCHAR2(20)
    MANUFACTURER_PARTY_ID VARCHAR2(20)
    FACILITY_ID VARCHAR2(20)
    INTRODUCTION_DATE TIMESTAMP(6)
    SUPPORT_DISCONTINUATION_DATE TIMESTAMP(6)
    SALES_DISCONTINUATION_DATE TIMESTAMP(6)
    SALES_DISC_WHEN_NOT_AVAIL CHAR(1)
    INTERNAL_NAME VARCHAR2(255)
    BRAND_NAME VARCHAR2(100)
    COMMENTS VARCHAR2(255)
    =========
    CREATE TABLE PROD_CONFIG_PROD_CONFIG_OPTION (
    PRODUCT_ID VARCHAR2(20),
    CONFIG_ITEM_ID VARCHAR2(20),
    CONFIG_OPTION_ID VARCHAR2(20),
    PAGE_NUM_TO NUMBER(18),
    ALTERNATE_PAGE_NUM_TO1 NUMBER(18),
    ALTERNATE_PAGE_NUM_TO2 NUMBER(18),
    ALTERNATE_PAGE_NUM_TO3 NUMBER(18),
    LAST_UPDATED_STAMP TIMESTAMP(6),
    LAST_UPDATED_TX_STAMP TIMESTAMP(6),
    CREATED_STAMP TIMESTAMP(6),
    CREATED_TX_STAMP TIMESTAMP(6),
    CONSTRAINT PK_PROD_CAT_CONFIG_MOD PRIMARY KEY (PRODUCT_ID),
    CONSTRAINT FK_PRODUCT_ID FOREIGN KEY (PRODUCT_ID) REFERENCES PRODUCT(PRODUCT_ID),
    CONSTRAINT FK_CONFIG_ITEM_ID FOREIGN KEY (CONFIG_ITEM_ID) REFERENCES PRODUCT_CONFIG_ITEM(CONFIG_ITEM_ID),
    CONSTRAINT FK_CONFIG_OPTION_ID FOREIGN KEY (CONFIG_OPTION_ID) REFERENCES PRODUCT_CONFIG_OPTION(CONFIG_OPTION_ID) )
    TABLESPACE DATA_SMALL
    i try to create this table if i omit 3rd foreign key constraint then table successfully created.but including trd foreign key constraint it return error "ORA-02270: no matching unique or primary key for this column-list"
    i checked everything is it possible to create foreign key from composite key in other table.

    And
    CONSTRAINT FK_CONFIG_OPTION_ID FOREIGN KEY (CONFIG_ITEM_ID,CONFIG_OPTION_ID) REFERENCES PRODUCT_CONFIG_OPTION(CONFIG_ITEM_ID,CONFIG_OPTION_ID)
    ?

  • DELETING child record of same table..  qry  required( complicated)

    hai
    how to delete the child record of same table...?
    Here is the example...
    CREATE TABLE TDA
    (     PKNODAVE VARCHAR2(7 BYTE) NOT NULL ENABLE,
         DTCREATION DATE,
         DAVETRANSFERT VARCHAR2(7 BYTE),
         PKPARC NUMBER(5,0)
    ALTER TABLE TDA ADD CONSTRAINT PK_TDAV8 PRIMARY KEY (PKNODAVE)
    ALTER TABLE TDA ADD CONSTRAINT FK_TDA1 FOREIGN KEY (DAVETRANSFERT)
         REFERENCES TDA (PKNODAVE) ENABLE
    REM INSERTING into TDA
    Insert into TDA (PKNODAVE,DTCREATION,DAVETRANSFERT,PKPARC) values ('1',to_date('05-JAN-10','DD-MON-RR'),'1',10);
    Insert into TDA (PKNODAVE,DTCREATION,DAVETRANSFERT,PKPARC) values ('2',to_date('05-JAN-10','DD-MON-RR'),'2',10);
    Insert into TDA (PKNODAVE,DTCREATION,DAVETRANSFERT,PKPARC) values ('3',to_date('05-JAN-10','DD-MON-RR'),'3',10);
    Insert into TDA (PKNODAVE,DTCREATION,DAVETRANSFERT,PKPARC) values ('4',to_date('05-JAN-10','DD-MON-RR'),null,10);
    Insert into TDA (PKNODAVE,DTCREATION,DAVETRANSFERT,PKPARC) values ('5',to_date('05-JAN-10','DD-MON-RR'),'4',14);
    Insert into TDA (PKNODAVE,DTCREATION,DAVETRANSFERT,PKPARC) values ('6',to_date('05-JAN-10','DD-MON-RR'),'5',15);
    DELETE FROM TDA WHERE davetransfert IN ( SELECT PKNODAVE FROM TDA WHERE PKPARC='10')
    ERROR: FK_TDA1 CHILD RECORD FOUND...
    Pls give me the suggestions to solve this
    S

    You could try with a recursive procedure like this
    Processing ...
    select *
    from TDA
    Query finished, retrieving results...
    PKNODAVE      DTCREATION    DAVETRANSFERT   PKPARC  
    1                   05/01/10 1                     10
    2                   05/01/10 2                     10
    3                   05/01/10 3                     10
    4                   05/01/10                       10
    5                   05/01/10 4                     14
    6                   05/01/10 5                     15
    6 row(s) retrieved
    Processing ...
    declare
         cursor c is
              SELECT PKNODAVE FROM TDA WHERE PKPARC='10';
         procedure tda_cascade_delete(
                   del_PKNODAVE in varchar2
         as
              cursor sons is
                   select PKNODAVE
                   from TDA
                   where DAVETRANSFERT = del_PKNODAVE
                        and PKNODAVE <> DAVETRANSFERT;
         begin
              for x in sons loop
                   tda_cascade_delete(x.PKNODAVE);
              end loop;
              delete TDA
              where PKNODAVE = del_PKNODAVE;
         end;
    begin
         for x in c loop
              tda_cascade_delete(x.PKNODAVE);
         end loop;
    end;
    Processing ...
    select *
    from TDA
    Query finished, retrieving results...
    PKNODAVE      DTCREATION    DAVETRANSFERT   PKPARC  
    0 row(s) retrievedPS. A connect by subquery of the type
    delete tab
    where pk in (
              select fk
              from tab
              start with <my condition>
                   connect by fk = prior pk
         ) or <my condition>l;wouldn't generally work because it could try to delete a record before its children.
    Bye Alessandro

  • Problem in deleting child record

    Hi,
    I have a requirement to remove the child records.
    I have two database tables (without any foreign key or database constraints). I have created EOs (ParentEO and ChildEO) and Association. I have created view objects (ParentVO with a transient attribute called "SelectFlag" and ChildVO) based on EOs.
    I have created a MollyViewLink and created Application module (MollyAM) .VOs are associated with AM.
    For detail records, I have created delete icon and I have written below code to handle the deleteChild event in detail region's controller:
    public void processFormRequest(OAPageContext pageContext, OAWebBean webBean)
    super.processFormRequest(pageContext, webBean);
    if ("deleteChild".equals(pageContext.getParameter(EVENT_PARAM)))
    MollyAMImpl am = (MollyAMImpl)pageContext.getApplicationModule(webBean);
    String rowReference = pageContext.getParameter(OAWebBeanConstants.EVENT_SOURCE_ROW_REFERENCE);
    System.out.println("Child ROW Reference =="+rowReference);
    MollyUserDetailsVORowImpl voRow = (MollyUserDetailsVORowImpl)am.findRowByRef(rowReference);
    String parentID = voRow.getId().toString();
    System.out.println("ID is : "+ parentID);
    voRow.remove();
    System.out.println("Child row deleted successfully...");
    am.getTransaction().commit();
    When I click on delete icon at child record, I get below SOP messages:
    Child ROW Reference ==MollyAM.MollyUserDetailsVO_MollyViewLink_MollyUserDetailsVO:MollyUserDetailsVO_MollyViewLink_MollyUserDetailsVO_0{null}
    ID is : 52
    Child row deleted successfully...
    Child record is also being removed from UI. But when I query the database, I can still see the records there. For me, it seems like commit is not affecting the child table.
    Similar code to delete the parent record is working fine.
    Thanks!!!

    Hi Vinod ,
    I am deleting condition record number if  know any function module  please let me know
    problem happing in PRD for particular condition numer it showing INTERNAL ERROR (This is the condition table A923)
    that condition number is their in KONH but not their in KONP because of that  INTERNAL ERROR occuring
    for that i have writen code for that deleting the condition number  ....
    if know any thing please let me know

  • Deleting Child Records

    I'm a bit confused on how to accomplish the deletion of child records in a master/detail relationship.
    I have a master table and a child table. I created a foreign link between the tables. On my detail table, I have a Delete button, which I would like to use for removing child records. I understand for the master table, I will need to enable cascade delete to remove the master and all children records.
    Whenever I try to delete a child record I get the following error, integrity constraint - violated child record found. I understand the error, but how can I remove a single child record without deleting the master record. For example, I may have a 1 master record and 20 child records. I only want to remove one of the child records. The deletion seems to work fine when using AppModule or SQL Developer. Thanks.

    Thanks Surendrams. Your question made me take another closer look. Apparently, I was calling the Delete operation from the master table. I added another Delete operation in the Bindings from my child table and the deletion is now working. I should have caught this the first time. Thanks.

  • Deleting Child records which are not associated to any parent

    Hi
    We have seen that in the application though the Activty records has been deleted the child records like sample dropped and the roduct details has remained in the system. This happened cos in R18 when contact was deleted activty got deleted but the Activity child records remained in the application.
    we found that child records are present by looking into record utilization.
    Wanted to know if there is any way to delete these child records from teh application cos we are unable to query for them from UI as well as via webservices.
    any pointers would be helpful.
    -MR

    There is not a reporting subject area or folder available on Books. The workaround we employed was to create a field on the entity that was assigned books and that field was checked when the books were assigned. We are using web services to assign books and the web services also updates the field "Books Assigned". This gives us a way of reporting on that field to see those records without book assigned.

  • Syntax for creating foreign key across users in a database

    There are two user present A,B.They are granted all privileges.Now in USER A, there is a table PARENT whose primary key is PARENT_NO.In USER B I have created a table CHILD whose primary key is CHILD_NO.
    In the CHILD table of USER B, I want to create a foreign key relation to the PARENT table of USER A.For this I have created a column CHILD_PARENT_NO in the CHILD table.If anybody knows the syntax please post the syntax for creating the required foreign key relationship?

    Please post your code. Cut'n'paste from SQL*Plus like this...
    SQL> conn a/a
    Connected.
    SQL> desc t1
    Name                                      Null?    Type
    COL1                                               NUMBER
    COL2                                               VARCHAR2(10)
    SQL> grant references on t1 to b;
    Grant succeeded.
    SQL> conn b/b
    SQL> create synonym a_t for a.t1;
    Synonym created.
    SQL> alter table test add constraint fk foreign key (n) references a_t(col1);
    Table altered.
    SQL> Note that Oracle will translate the synonym anyway...
    SQL> select constraint_name, r_owner, r_constraint_name
      2  from  user_constraints
      3  where table_name = 'TEST'
      4  /
    CONSTRAINT_NAME R_OWNER R_CONSTRAINT_NAME
    FK              A       T1_PK
    SQL> By the way, this ...
    GRANT ALL PRIVILEGES TO B;... is a mindbendingly unsafe way of proceeding. In real life you would have given user B the power to utterly destroy your database. It's always easier to start with good habits than to break bad ones so please get used to granting only the minimum set of privileges necessary.
    Cheers, APC

  • Finding foreign keys of a child table,grandchild and all dependendents

    Hi All,
    I just came up with this sceanrio
    I have to delete a record in a parent table with a condition provided will have to find all the child tables depends on it and should recursively find all the dependents of the child table.
    How to achieve this.Please help with a query or guide.Thanks in advance

    Thanks visakh it gave me an idea and this script helped me
    DECLARE @mytable VARCHAR(30) SET @mytable = 'test'
    DECLARE @RecordID VARCHAR(8)
    SET @RecordID = '00000001'
    DECLARE @Order INT SET @Order = 0
    DECLARE @Count INT
    declare @tblname varchar(100),@query NVARCHAR(max)
    if OBJECT_ID('tempdb..#OrderList','U') is not null
    DROP TABLE #OrderList
    CREATE TABLE #TEMP
    OrderNo INT,
    TableName VARCHAR(50)
    CREATE TABLE #OrderList
    RecordNo INT,
    OrderNo INT,
    TableName VARCHAR(50)
    INSERT INTO #TEMP
    VALUES ( @Order,
    @mytable )
    WHILE ( EXISTS(SELECT TableName
    FROM #TEMP
    WHERE OrderNo = @Order) )
    BEGIN
    SET @Order= @Order + 1;
    INSERT INTO #TEMP
    SELECT @Order,
    t1.TABLE_NAME AS PointsFrom
    FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS r
    JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS t1
    ON t1.CONSTRAINT_NAME = r.CONSTRAINT_NAME
    JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS t2
    ON t2.CONSTRAINT_NAME = r.UNIQUE_CONSTRAINT_NAME
    WHERE t2.table_name IN (SELECT TableName
    FROM #TEMP
    WHERE OrderNo = ( @Order - 1 ))
    END
    INSERT INTO #OrderList
    SELECT Row_number() OVER (ORDER BY OrderNo, TableName),
    #TEMP.OrderNo,
    #TEMP.TableName
    FROM #TEMP
    DROP TABLE #TEMP
    --SELECT * FROM #OrderList
    SET @Count = (SELECT Max(RecordNo)
    FROM #OrderList)
    WHILE (@Count <> 0 )
    BEGIN
    select @tblname = TableName FROM #OrderList WHERE RecordNo = @Count
    select @query = 'DELETE from '+ @tblname
    select @query
    exec sp_executesql @query
    SET @Count = @Count-1
    END

  • To delete child records manually without using oracle's delete cascade

    Hi all
    I have to write a procedure that accepts schema name, table name and column value as parameters....I knew that i need to use metadata to do that deleting manually....I am a beginner...can somebody help me with the procedure?

    Hi Guru,
    They told me to use this procedure...but this procedure isn't working...can you help me to understand this procedure?
    CREATEOR REPLACE PROCEDURE delete_cascade(
        table_owner          VARCHAR2,
        parent_table         VARCHAR2,
        where_clause         VARCHAR2
    )IS
        /*   Example call:  execute delete_cascade('MY_SCHEMA', 'MY_MASTER', 'where ID=1'); */
        child_cons     VARCHAR2(30);
        parent_cons    VARCHAR2(30);
        child_table    VARCHAR2(30);
        child_cols     VARCHAR(500);
        parent_cols    VARCHAR(500);
        delete_command VARCHAR(10000);
        new_where_clause VARCHAR2(10000);
        /* gets the foreign key constraints on other tables which depend on columns in parent_table */
        CURSOR cons_cursor IS
            SELECT owner, constraint_name, r_constraint_name, table_name, delete_rule
              FROM all_constraints
             WHERE constraint_type ='R'
               AND delete_rule ='NO ACTION'
               AND r_constraint_name IN(SELECT constraint_name
                                           FROM all_constraints
                                          WHERE constraint_type IN('P','U')
                                            AND table_name = parent_table
                                            AND owner = table_owner)
               ANDNOT table_name = parent_table;-- ignore self-referencing constraints
        /* for the current constraint, gets the child columns and corresponding parent columns */
        CURSOR columns_cursor IS
            SELECT cc1.column_name AS child_col, cc2.column_name AS parent_col
              FROM all_cons_columns cc1, all_cons_columns cc2
             WHERE cc1.constraint_name = child_cons
               AND cc1.table_name = child_table
               AND cc2.constraint_name = parent_cons
               AND cc1.position = cc2.position
            ORDERBY cc1.position;
    BEGIN
        /* loops through all the constraints which refer back to parent_table */
        FOR cons IN cons_cursor LOOP
            child_cons   := cons.constraint_name;
            parent_cons  := cons.r_constraint_name;
            child_table  := cons.table_name;
            child_cols   :='';
            parent_cols  :='';
            /* loops through the child/parent column pairs, building the column lists of the DELETE statement */
            FOR cols IN columns_cursor LOOP
                IF child_cols ISNULLTHEN
                    child_cols  := cols.child_col;
                ELSE
                    child_cols  := child_cols ||', '|| cols.child_col;
                ENDIF;
                IF parent_cols ISNULLTHEN
                    parent_cols  := cols.parent_col;
                ELSE
                    parent_cols  := parent_cols ||', '|| cols.parent_col;
                ENDIF;
            END LOOP;
            /* construct the WHERE clause of the delete statement, including a subquery to get the related parent rows */
            new_where_clause  :=
                'where ('|| child_cols ||') in (select '|| parent_cols ||' from '|| table_owner ||'.'|| parent_table ||
                ' '|| where_clause ||')';
            delete_cascade(cons.owner, child_table, new_where_clause);
        END LOOP;
        /* construct the delete statement for the current table */
        delete_command  :='delete from '|| table_owner ||'.'|| parent_table ||' '|| where_clause;
        -- this just prints the delete command
        DBMS_OUTPUT.put_line(delete_command ||';');
            EXECUTE IMMEDIATE delete_command;
        -- remember to issue a COMMIT (not included here, for safety)
    END;Edited by: BluShadow on 09-Oct-2012 16:05
    added {noformat}{noformat} tags for readability.  Please read: {message:id=9360002} and learn to do this yourself in future.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

  • Chaging primary key value when child record present

    Please tell me how to change the primary key value when it's child record is present.

    Well something like INSERT new primary key, UPDATE child records, DELETE old primary key would seem fairly obvious.
    Using deferrable constraints may make the process rather simpler.
    If on the other hand you are looking for UPDATE cascade functionality, Tom Kyte has an article regarding implementing this.
    http://asktom.oracle.com/tkyte/update_cascade/index.html

  • Foreign-key autocreation in child table giving issue in the application

    Hi,
      I am facing an issue with partitioning a table that foreign key relationship is created on the original table with interim table. This gives exception in the application because of its existence. Please suggest me how to get rid of this issue.
    Let's say my table T_TABLENAME has to be partitioned. It has a child table T_CHILD_TABLENAME which references (FK_T1) ID column of T_TABLENAME.
    While partitioning, COPY_TABLE_DEPENDENTS function copies/creates the key/index/trigger objects for the interim table. [I need copy_constraints => TRUE in COPY_TABLE_DEP call], Fine.
    But, after partitioning is done, the foreign key (TMP$$_FK_T1) object exists with the child table which should absolutely not happen as this forms dependency with interim table as well along with parent table.
    Here my script goes:
    i) Creating interim table
    CREATE TABLE T_TABLENAME_PT
    PARTITION BY RANGE (CREATED_DATE)
    (PARTITION P_2007 VALUES LESS THAN (TO_DATE('01-JAN-2008','dd-MON-yyyy')),
    PARTITION P_2009 VALUES LESS THAN (TO_DATE('01-JAN-2010','dd-MON-yyyy')),
    PARTITION P_2011 VALUES LESS THAN (TO_DATE('01-JAN-2012','dd-MON-yyyy')),
    PARTITION P_2012 VALUES LESS THAN (TO_DATE('01-JAN-2013','dd-MON-yyyy')),
    PARTITION P_RECENT VALUES LESS THAN (MAXVALUE))
    AS SELECT * FROM T_TABLENAME WHERE 1=2;
    ii) Partitioning Script
    declare
      v_username varchar2(50);
      v_exception varchar2(220);
      l_num_errors PLS_INTEGER;
      v_source_table  varchar2(35) := 'T_TABLENAME';
      v_interim_table varchar2(35) := 'T_TABLENAME_PT';
    BEGIN
      select USERNAME into v_username from USER_USERS where rownum <= 1;
      begin
          DBMS_REDEFINITION.CAN_REDEF_TABLE(v_username, v_source_table, DBMS_REDEFINITION.CONS_USE_PK);
          DBMS_REDEFINITION.START_REDEF_TABLE(
            uname      => v_username,
            orig_table => v_source_table,
            int_table  => v_interim_table);
          DBMS_REDEFINITION.COPY_TABLE_DEPENDENTS(
            uname      => v_username,
            orig_table => v_source_table,
            int_table  => v_interim_table,
            copy_indexes => 1,
            copy_triggers => TRUE,
            copy_constraints => TRUE,
            copy_privileges => TRUE,
            ignore_errors => TRUE,
            num_errors => l_num_errors);
          DBMS_REDEFINITION.SYNC_INTERIM_TABLE(v_username, v_source_table, v_interim_table);
          begin
           DBMS_REDEFINITION.FINISH_REDEF_TABLE(
            UNAME      => v_username,
            ORIG_TABLE => v_source_table,
            INT_TABLE  => v_interim_table);       
         EXCEPTION
         WHEN OTHERS THEN
           DBMS_REDEFINITION.ABORT_REDEF_TABLE(
            UNAME      => v_username,
            ORIG_TABLE => v_source_table,
            INT_TABLE  => v_interim_table);
          end;     
          exception
              when others then
                v_exception :=substr(SQLERRM,1,150);
      end;
    exception
      when others then
        v_exception := substr(SQLERRM,1,175);
    END;

    Thanks for your information. I am using Oracle Database 10g Enterprise Edition Release 10.1.0.2.0 - 64bit.
    1) I am logging the exceptions in a logger table.
    2) If CAN_REDEF_TABLE gives exception, flow goes to the final EXCEPTION block and program terminates. So if no exceptions, the other steps comes into the flow of execution.
    Complete Details
    (1) Parent Table (existing): T_SOH_SUBREQ_INSTALLATION_ADDR
    create table T_SOH_SUBREQ_INSTALLATION_ADDR
      ACCOUNT_ADDRESS_ID  NUMBER(10),
      SUBREQ_ADDRESS_ID   NUMBER(10) not null,
      COMMUNITY_ID        NUMBER(10),
      STREET_ID           NUMBER(10),
      BUILDING_ID         NUMBER(10),
      CREATED_USER_ID     VARCHAR2(40) not null,
      MODIFIED_USER_ID    VARCHAR2(40) not null,
      CREATED_DATE        TIMESTAMP(6) not null,
      MODIFIED_DATE       TIMESTAMP(6) not null,
      DELETION_STATUS     CHAR(1) not null
    alter table T_SOH_SUBREQ_INSTALLATION_ADDR
      add constraint PK_T_SOH_SUBREQ_INST_ADDR primary key (SUBREQ_ADDRESS_ID);
    alter table T_SOH_SUBREQ_INSTALLATION_ADDR
      add constraint FK_T_SOH_SUBREQ_INSTALLATIO624 foreign key (ACCOUNT_ADDRESS_ID)
      references T_SOH_ACCT_INSTALLATION_ADDR (ACCOUNT_ADDRESS_ID);
    (2) Child Table (existing): T_SOH_SUBREQ_LINKED_INST_ADDR
    create table T_SOH_SUBREQ_LINKED_INST_ADDR
      CREATED_DATE      TIMESTAMP(6) not null,
      CREATED_USER_ID   VARCHAR2(40) not null,
      MODIFIED_DATE     TIMESTAMP(6) not null,
      MODIFIED_USER_ID  VARCHAR2(20) not null,
      DELETION_STATUS   CHAR(1) not null,
      SUBREQ_ADDRESS_ID NUMBER(10) not null,
      SUBREQUEST_ID     NUMBER(10) not null,
      CIRCUIT_POINT     NUMBER(10)
    alter table T_SOH_SUBREQ_LINKED_INST_ADDR
      add constraint PK_T_SOH_SUBREQ_LINK_INST_ADDR primary key (SUBREQ_ADDRESS_ID, SUBREQUEST_ID);
    alter table T_SOH_SUBREQ_LINKED_INST_ADDR
      add constraint FK_T_SOH_SUBREQ_LINKED_INST626 foreign key (SUBREQ_ADDRESS_ID)
      references T_SOH_SUBREQ_INSTALLATION_ADDR (SUBREQ_ADDRESS_ID);
    (3) Partitioning is done on Parent Table
    CREATE TABLE T_TMP_PARTITION_LOGS
      LOG_MSG  VARCHAR2(250),
      LOG_TIME TIMESTAMP(6)
    CREATE TABLE T_SOH_SUBREQ_INSTALL_ADDR_PT
    PARTITION BY RANGE (CREATED_DATE)
    (PARTITION P_2007 VALUES LESS THAN (TO_DATE('01-JAN-2008','dd-MON-yyyy')),
    PARTITION P_2009 VALUES LESS THAN (TO_DATE('01-JAN-2010','dd-MON-yyyy')),
    PARTITION P_2011 VALUES LESS THAN (TO_DATE('01-JAN-2012','dd-MON-yyyy')),
    PARTITION P_2012 VALUES LESS THAN (TO_DATE('01-JAN-2013','dd-MON-yyyy')),
    PARTITION P_RECENT VALUES LESS THAN (MAXVALUE))
    AS SELECT * FROM T_SOH_SUBREQ_INSTALLATION_ADDR WHERE 1=2;
    insert into t_tmp_partition_logs(log_msg,log_time) values('01_CreateTable: T_SOH_SUBREQ_INSTALL_ADDR_PT Table Created', systimestamp);
    (4) Script for REDEFINITION
    declare
      v_username varchar2(50);
      v_exception varchar2(220);
      l_num_errors PLS_INTEGER;
      v_source_table  varchar2(35) := 'T_SOH_SUBREQ_INSTALLATION_ADDR';
      v_interim_table varchar2(35) := 'T_SOH_SUBREQ_INSTALL_ADDR_PT';
      v_file_name     varchar2(20) := '02_Redefine';
    BEGIN
      insert into t_tmp_partition_logs(log_msg,log_time) values(v_file_name || '.sql --> Starts', systimestamp);
      select USERNAME into v_username from USER_USERS where rownum <= 1;
      insert into t_tmp_partition_logs(log_msg,log_time) values(v_file_name || ': UserName-'|| v_username, systimestamp);
      begin
          DBMS_REDEFINITION.CAN_REDEF_TABLE(v_username, v_source_table, DBMS_REDEFINITION.CONS_USE_PK);
          insert into t_tmp_partition_logs(log_msg,log_time) values(v_file_name ||': '|| v_source_table ||' After CAN_REDEF_TABLE', systimestamp);
          DBMS_REDEFINITION.START_REDEF_TABLE(
            uname      => v_username,
            orig_table => v_source_table,
            int_table  => v_interim_table);
          insert into t_tmp_partition_logs(log_msg,log_time) values(v_file_name ||': '|| v_source_table ||' After START_REDEF_TABLE', systimestamp);
          DBMS_REDEFINITION.COPY_TABLE_DEPENDENTS(
            uname      => v_username,
            orig_table => v_source_table,
            int_table  => v_interim_table,
            copy_indexes => 1,
            copy_triggers => TRUE,
            copy_constraints => TRUE,
            copy_privileges => TRUE,
            ignore_errors => TRUE,
            num_errors => l_num_errors);
          insert into t_tmp_partition_logs(log_msg,log_time) values(v_file_name ||': '|| v_source_table ||' After COPY_TABLE_DEPENDENTS - l_num_errors:' || l_num_errors, systimestamp);
          DBMS_REDEFINITION.SYNC_INTERIM_TABLE(v_username, v_source_table, v_interim_table);
          insert into t_tmp_partition_logs(log_msg,log_time) values(v_file_name ||': After SYNC_INTERIM_TABLE on '|| v_source_table, systimestamp);
          begin
           DBMS_REDEFINITION.FINISH_REDEF_TABLE(
            UNAME      => v_username,
            ORIG_TABLE => v_source_table,
            INT_TABLE  => v_interim_table);       
          insert into t_tmp_partition_logs(log_msg,log_time) values(v_file_name ||': After FINISH_REDEF_TABLE on '|| v_source_table, systimestamp);
         EXCEPTION
         WHEN OTHERS THEN
           DBMS_REDEFINITION.ABORT_REDEF_TABLE(
            UNAME      => v_username,
            ORIG_TABLE => v_source_table,
            INT_TABLE  => v_interim_table);
           insert into t_tmp_partition_logs(log_msg,log_time) values(v_file_name ||': Aborted '|| v_source_table, systimestamp);
          end;     
        insert into t_tmp_partition_logs(log_msg,log_time) values(v_file_name ||': '|| v_source_table ||' redefined', systimestamp);
          exception
              when others then
                v_exception :=substr(SQLERRM,1,150);
                insert into t_tmp_partition_logs(log_msg,log_time) values(v_file_name ||'-EXCEPTION:'|| v_source_table ||'-' || v_exception, systimestamp);
      end;
      insert into t_tmp_partition_logs(log_msg,log_time) values(v_file_name ||'.sql <-- Ends', systimestamp);
    exception
      when others then
        v_exception := substr(SQLERRM,1,175);
        insert into t_tmp_partition_logs(log_msg,log_time) values(v_file_name ||'-EXCEPTION:' || v_exception, systimestamp);
    END;
    ==> NOW THE ISSUE
    My child table T_SOH_SUBREQ_LINKED_INST_ADDR is having another foreign key column TMP$$_FK_T_SOH_SUBREQ_LIN4 with the interim table T_SOH_SUBREQ_INSTALL_ADDR_PT.

  • Create Foreign Keys between two Schemata

    Hello,
    I use Oracle 10g and I trying to create a ForeignKey constraint between two tables in different schemata.
    This is my DDL-Script
    SQL> CREATE TABLE PROJECT.LOCATION (
    ID INTEGER NOT NULL,
    MAIN INTEGER,
    KURZ VARCHAR(40),
    NAME VARCHAR(40),
    STRASSE VARCHAR(40),
    ORT VARCHAR(40),
    TELEFON VARCHAR(40),
    FAX VARCHAR(40),
    EMAIL VARCHAR(40),
    PLZ VARCHAR(40),
    CONSTRAINT PK_LOCATION PRIMARY KEY (ID)
    Tablespace PROJECT;
    CREATE TABLE Diary.Diary (
    ID INTEGER NOT NULL,
    LOCATION_ID INTEGER NOT NULL,
    CONSTRAINT PK_Diary PRIMARY KEY (ID)
    Tablespace Diary;
    ALTER TABLE Diary.Diary
    ADD CONSTRAINT FK_Diary_Has_LOCATION
    FOREIGN KEY (LOCATION_ID) REFERENCES PROJECT.LOCATION (ID);
    This is the Message that gives my SQLplus :
    SQL> ALTER TABLE Diary.Diary
    2 ADD CONSTRAINT FK_Diary_Has_LOCATION
    3 FOREIGN KEY (LOCATION_ID) REFERENCES PROJECT.LOCATION (ID);
    FOREIGN KEY (LOCATION_ID) REFERENCES PROJECT.LOCATION (ID)
    FEHLER in Zeile 3:
    ORA-00942: Tabelle oder View nicht vorhanden
    All Grants (select,alter,references) are given to the User for the tables.
    Whats then Problem?

    You miss some priviledge:
    SQL> create user project identified by project;
    Utente creato.
    SQL> grant connect, resource to project;
    Concessione riuscita.
    SQL> create user diary identified by diary;
    Utente creato.
    SQL> grant connect, resource to diary;
    Concessione riuscita.
    SQL> CREATE TABLE PROJECT.LOCATION (
      2  ID INTEGER NOT NULL,
      3  MAIN INTEGER,
      4  KURZ VARCHAR(40),
      5  NAME VARCHAR(40),
      6  STRASSE VARCHAR(40),
      7  ORT VARCHAR(40),
      8  TELEFON VARCHAR(40),
      9  FAX VARCHAR(40),
    10  EMAIL VARCHAR(40),
    11  PLZ VARCHAR(40),
    12  CONSTRAINT PK_LOCATION PRIMARY KEY (ID)
    13  )
    14  ;
    Tabella creata.
    SQL> CREATE TABLE Diary.Diary (
      2  ID INTEGER NOT NULL,
      3  LOCATION_ID INTEGER NOT NULL,
      4  CONSTRAINT PK_Diary PRIMARY KEY (ID)
      5  )
      6  ;
    Tabella creata.
    SQL> ALTER TABLE Diary.Diary
      2  ADD CONSTRAINT FK_Diary_Has_LOCATION
      3  FOREIGN KEY (LOCATION_ID) REFERENCES PROJECT.LOCATION (ID);
    FOREIGN KEY (LOCATION_ID) REFERENCES PROJECT.LOCATION (ID)
    ERRORE alla riga 3:
    ORA-00942: tabella o vista inesistente
    -- DIARY CAN'T SEE PROJECT.LOCATION
    SQL> grant select on project.location to diary;
    Concessione riuscita.
    SQL> ALTER TABLE Diary.Diary
      2  ADD CONSTRAINT FK_Diary_Has_LOCATION
      3  FOREIGN KEY (LOCATION_ID) REFERENCES PROJECT.LOCATION (ID);
    FOREIGN KEY (LOCATION_ID) REFERENCES PROJECT.LOCATION (ID)
    ERRORE alla riga 3:
    ORA-01031: privilegi insufficienti
    -- DIARY CAN SEE PROJECT.LOCATION BUT CAN'T REFERENCE IT
    SQL> grant references on project.location to diary;
    Concessione riuscita.
    SQL> ALTER TABLE Diary.Diary
      2  ADD CONSTRAINT FK_Diary_Has_LOCATION
      3  FOREIGN KEY (LOCATION_ID) REFERENCES PROJECT.LOCATION (ID);
    Tabella modificata.
    -- NOW IT'S ALL OK!!Max
    [My Italian Oracle blog|http://oracleitalia.wordpress.com/2009/12/18/table-elimination-oppure-join-elimination-lottimizzatore-si-libera-della-zavorra/]

Maybe you are looking for

  • Particular Vendor Account assignment in Financial Statement Version

    Hello,         I am preparing Financial Statement Version. There are around 50 vendors and out of that 2 vendors have been paid in advance. I need to show that 2 particular vendors in Financial Statement Version, the problem is there is only one reco

  • Pictures in Microsoft documents.

    Appleworks does not appear to recognise or format microsoft documents with embedded pictures. i.e.the text,if any, is translated but the pictures disappear - any ideas?

  • OBIEE , ADF integration

    Hi All, My requirement is show dashboard on my adf screen based on user role . For this i created three dashboards Dashboard1-   assigned to role1 Dashboard2-  assigned to role2 Dashboard3-   assigned to role3 . I created a adf page which contains th

  • [SOLVED]No sound. Intel Corporation 82801DB/DBL/DBM (ICH4/ICH4-L/ICH4

    00:1f.5 Multimedia audio controller: Intel Corporation 82801DB/DBL/DBM (ICH4/ICH4-L/ICH4-M) AC'97 Audio Controller (rev 01) ^ That's my sound card. I went on IRC and asked for help configuring it but nothing would work. I'm sorry I don't have more in

  • Video Stream App wont work

    After realising that iCloud doesnt upload videos I purchased the Video Stream app recomended. When I open it it gives the option to upload a video. I do this, the video starts uploading (it says uploading video), then everything stops and it goes bac