Parent - Child Table Insert Trigger

Hello,
I need some help with an Insert Trigger. I want to Insert some field data from 'Table A' to 'Table B' based on a PK and FK. Does anyone have any sample code?
<code>
Table A
SEQ_NO --PK
FIELD A
FIELD B
FIELD C
Table B
FK_SEQ_NO
FIELD B
FIELD C
<code>
When data is saved in 'Table A' I need to populate the 'FK_SEQ_NO' based on the saved value from 'Table A' 'SEQ_NO' along with the FIELD B and FIELD C values saved to Table B.
Any help is really appreciated, thanks.

Hi,
How about this:
create or replace TRIGGER rmdb_work_packages_biudr_trg
BEFORE INSERT OR UPDATE OR DELETE ON rmdb_work_packages
FOR EACH ROW
DECLARE
  l_module_name          CONSTANT VARCHAR2(100) :=  'tpsdev.rmdb_work_packages_biudr_trg';
BEGIN
  IF INSERTING THEN
    -- generate a PK sequence if not already set
    IF :new.work_package_id IS NULL THEN
      SELECT rmdb_work_packages_seq.NEXTVAL
      INTO :new.work_package_id
      FROM dual;
    END IF;
    -- populate audit columns
    :NEW.created_by := NVL(v('APP_USER'),user);
    :NEW.creation_date := SYSDATE;
  END IF;
  IF INSERTING OR UPDATING THEN
    IF :new.business_sign_off_flag IS NULL THEN
      -- set the business_sign_off_flag = 'N' if it is null
      :new.business_sign_off_flag := 'N';
    END IF;
    IF :new.at_risk_flag IS NULL THEN
      -- set the at_risk_flag = 'N' if it is null
      :new.at_risk_flag := 'N';
    END IF;
    IF :new.resource_required_flag IS NULL THEN
      -- set the resource_required_flag = 'Y' if it is null
      :new.resource_required_flag := 'N';
    END IF;
    IF :new.contains_patches_flag IS NULL THEN
      -- set the contains_patches_flag = 'Y' if it is null
      :new.contains_patches_flag := 'N';
    END IF;
    -- populate audit columns
    :NEW.last_updated_by := NVL(v('APP_USER'),user);
    :NEW.last_update_date := SYSDATE;
  END IF;
  IF INSERTING THEN
    INSERT INTO RMDB_WP_HISTORY
    WORK_PACKAGE_ID,
    PROJECT_ID,
    SERVICE_ID,
    RELEASE_ID,
    NAME,
    DESCRIPTION,
    COMMENTS,
    WP_TYPE_CODE,
    RESOURCE_REQUIRED_FLAG,
    WP_STATUS_CODE,
    CHANGE_PROBABILITY_CODE,
    CHANGE_IMPACT_CODE,
    APP_USER_ID_OWNER,
    APP_USER_ID_DEPUTY,
    WP_PRIORITY_CODE,
    PRIORITY_JUSTIFICATION,
    REQUIRED_LIVE_DATE,
    BUSINESS_SIGN_OFF_FLAG,
    AT_RISK_FLAG,
    CONTAINS_PATCHES_FLAG,
    PM_REFERENCE,
    MARVAL_NUMBER,
    RCD_NOTES,
    CREATED_BY,
    CREATION_DATE,
    LAST_UPDATED_BY,
    LAST_UPDATE_DATE
    VALUES
   :NEW.WORK_PACKAGE_ID,
   :NEW.PROJECT_ID,
   :NEW.SERVICE_ID,
   :NEW.RELEASE_ID,
   :NEW.NAME,
   :NEW.DESCRIPTION,
   :NEW.COMMENTS,
   :NEW.WP_TYPE_CODE,
   :NEW.RESOURCE_REQUIRED_FLAG,
   :NEW.WP_STATUS_CODE,
   :NEW.CHANGE_PROBABILITY_CODE,
   :NEW.CHANGE_IMPACT_CODE,
   :NEW.APP_USER_ID_OWNER,
   :NEW.APP_USER_ID_DEPUTY,
   :NEW.WP_PRIORITY_CODE,
   :NEW.PRIORITY_JUSTIFICATION,
   :NEW.REQUIRED_LIVE_DATE,
   :NEW.BUSINESS_SIGN_OFF_FLAG,
   :NEW.AT_RISK_FLAG,
   :NEW.CONTAINS_PATCHES_FLAG,
   :NEW.PM_REFERENCE,
   :NEW.MARVAL_NUMBER,
   :NEW.RCD_NOTES,
   :NEW.CREATED_BY,
   :NEW.CREATION_DATE,
   :NEW.LAST_UPDATED_BY,
   :NEW.LAST_UPDATE_DATE  
  END IF;
  IF UPDATING THEN
    INSERT INTO RMDB_WP_HISTORY
    WORK_PACKAGE_ID,
    PROJECT_ID,
    SERVICE_ID,
    RELEASE_ID,
    NAME,
    DESCRIPTION,
    COMMENTS,
    WP_TYPE_CODE,
    RESOURCE_REQUIRED_FLAG,
    WP_STATUS_CODE,
    CHANGE_PROBABILITY_CODE,
    CHANGE_IMPACT_CODE,
    APP_USER_ID_OWNER,
    APP_USER_ID_DEPUTY,
    WP_PRIORITY_CODE,
    PRIORITY_JUSTIFICATION,
    REQUIRED_LIVE_DATE,
    BUSINESS_SIGN_OFF_FLAG,
    AT_RISK_FLAG,
    CONTAINS_PATCHES_FLAG,
    PM_REFERENCE,
    MARVAL_NUMBER,
    RCD_NOTES,
    CREATED_BY,
    CREATION_DATE,
    LAST_UPDATED_BY,
    LAST_UPDATE_DATE
    VALUES
    :NEW.WORK_PACKAGE_ID,
    :NEW.PROJECT_ID,
    :NEW.SERVICE_ID,
    :NEW.RELEASE_ID,
    :NEW.NAME,
    :NEW.DESCRIPTION,
    :NEW.COMMENTS,
    :NEW.WP_TYPE_CODE,
    :NEW.RESOURCE_REQUIRED_FLAG,
    :NEW.WP_STATUS_CODE,
    :NEW.CHANGE_PROBABILITY_CODE,
    :NEW.CHANGE_IMPACT_CODE,
    :NEW.APP_USER_ID_OWNER,
    :NEW.APP_USER_ID_DEPUTY,
    :NEW.WP_PRIORITY_CODE,
    :NEW.PRIORITY_JUSTIFICATION,
    :NEW.REQUIRED_LIVE_DATE,
    :NEW.BUSINESS_SIGN_OFF_FLAG,
    :NEW.AT_RISK_FLAG,
    :NEW.CONTAINS_PATCHES_FLAG,
    :NEW.PM_REFERENCE,
    :NEW.MARVAL_NUMBER,
    :NEW.RCD_NOTES,
    :NEW.CREATED_BY,
    :NEW.CREATION_DATE,
    :NEW.LAST_UPDATED_BY,
    :NEW.LAST_UPDATE_DATE
  END IF;
  IF DELETING THEN
    DELETE FROM RMDB_WP_HISTORY
    WHERE WORK_PACKAGE_ID = :NEW.WORK_PACKAGE_ID;
  END IF;
END rmdb_work_packages_biudr_trg; There is also a trigger on the child table:
create or replace TRIGGER RMDB_WP_HISTORY_BIUDR_TRG
BEFORE INSERT OR UPDATE OR DELETE ON RMDB_WP_HISTORY
FOR EACH ROW
BEGIN
  IF INSERTING THEN
    -- generate a PK sequence if not already set
    IF :new.WP_HISTORY_ID    IS NULL THEN
       SELECT RMDB_WP_HISTORY_SEQ.NEXTVAL
       INTO :new.WP_HISTORY_ID
       FROM dual;
    END IF;
  END IF;
END RMDB_WP_HISTORY_BIUDR_TRG; Does that help?
Regards,
Martin

Similar Messages

  • Loading to Parent -Child Tables simultaneously

    I have a requirement to populate parent-child tables in a single interface simultaneoulsy. I couldnt find anyway to add multiple targets and am wondering why this key feature is absent in ODI. The same thing is easily achievable in BPEL.
    Could some one please advice a work around for this.
    Your help is much appreaciated

    ODI 11g does come with a new IKM 'IKM Oracle Multi Table Insert'. This does allow multi table inserts, but will require more than one interface.
    Oracle Multi-Table Inserts
    A new Integration KM for Oracle allows populating several target tables from a single source, reading the data only once. It uses the INSERT ALL statement.
    COMPONENT NAME: IKM Oracle Multi Table Insert
    COMPONENT VERSION: 11.1.2.4
    AUTHOR: Oracle
    COMPATIBILITY: ODI 11.1.1.3 and above
    DESCRIPTION:
         - Integrates data from one source into one to many Oracle target tables in append mode, using a multi-table insert statement (MTI).
    REQUIREMENTS:
         - Oracle Database 9iR1 or above
         - See BASIC CONFIGURATION section
    BASIC CONFIGURATION
         - This IKM must be used in integration interfaces that are sequenced in a Package:
              - The first interface of the Package must have a temporary target and the KM option DEFINE_QUERY set to YES.
              This first interface defines the structure of the SELECT clause of the multi-table insert statement (that is the source flow).
              - Subsequent integration interfaces must source from this temporary datastore and have the KM option IS_TARGET_TABLE set to YES.
              - The last interface of the Package must have the KM option EXECUTE set to YES in order to run the multi-table insert statement.
              - Do not set "Use Temporary Interface as Derived Table(Sub-Select)" set to true on any of the interfaces.
         - If large amounts of data are appended, consider to set the KM option OPTIMIZER_HINT to /*+ APPEND */.
    OPTIONS (Refer to the Option descriptions for more information on each option)
         - DEFINE_QUERY: Set to Yes if this interface describes the source query (SELECT clause of the statement). This interface must have a temporary target.
         - IS_TARGET_TABLE: Set to Yes this interface using the source query to load one of the target tables. This interface must source from an interface with a temporary target using this IKM and having the KM option DEFINE_QUERY set to YES.
         - EXECUTE: Set to Yes for the last interface in the Package. This interface will run the multi-table insert statement.
         - COMMIT: Commit transaction. This applies only to the last interface in the Package.
         - TRUNCATE: Set to Yes to truncate this interface target table.
         - CREATE_TARG_TABLE: Create target table? May only be used on target interfaces, but not on source interfaces (defining the source data).
         - OPTIMIZER_HINT: Hint for the multi-table insert statement.
    RESTRICTIONS:
         - This KM can only be used in integration interfaces that are part of a Package.
         - All source and target datastores need to reside on same data server.
         - Journalized source data is not supported.
         - Temporary indexes are not supported.
         - Flow/static control is not supported.
         - The TRUNCATE option cannot work, if the target table is referenced by another table (foreign key).

  • How can we archive Partioning in parent child tables in Normalised way.

    Hi Friends.
    Could you please suggest me
    How can we archive Partioning in parent child tables in Normalised way.
    Bill_parent(
    Bill_no number,
    Bill_date date .-- I want to create Partition on this column
    customer_id
    Bill_Child{
    bill_no number,
    Bill_c_no number,
    Item_code number
    Qty number
    Bill_Acsry{
    Bill_c_no number,
    acsry_it_code number,
    qty number
    Now for there Child Table I have also create a Bill_date column that is against Normalization
    i.e
    Bill_parent(
    Bill_no number,
    Bill_date date.
    customer_id
    ) Partion by Range (Bill_date).......................
    Bill_Child{
    bill_no number,
    Bill_c_no number,
    Item_code number
    Qty number,
    Bill_Date date,-- against normalisation
    }Partion by Range (Bill_date).......................
    Bill_Acsry{
    Bill_c_no number,
    acsry_it_code number,
    qty number,
    Bill_Date date,-- against normalisation
    }Partion by Range (Bill_date)....
    with regards
    Siddharth Singh([email protected])

    Looks like the new Reference Partitioning feature in 11g is what you want. In previous versions I think you're stuck with the denormalisation.

  • Insert Record with Parent/Child Tables doesn't work with Oracle - unlike AC

    Hi,
    I just Migrated a MS Access 2010 Database to an Oracle 11g Backend with the SQL Developer Tool.
    The Migration went fine, all the Tables and Views are migrated.
    I'm working with MS Access as Frontend.
    The application has some Datasheets with Subdatasheets with Parent/Child Relationship. (1-n Relationship)
    After changing to Oracle, it's not possible, to Insert a new Record in a Subdatasheet I always get the following Error Message:
    "The Microsoft Access database engine cannot find a record in the table 'xxxx' with key matching field(s) 'zzzzz'"
    It used to work perfect with the MS Access Backend, do I need a trigger which first adds the child Record ?
    Or what should I do?
    Thank you

    Hi Klaus,
    Thanks for your answer. I still haven't solved my problem. The only way would be to use a singel 1:n Relationship, but in fact I need a n:m Relationship.
    I tried the same scenario with a new Access Application, same result.
    To clearify my problem.
    Goal: Parent Form with Parent Records, Linked Child Form with Child Records in a Datasheet View => Insert of a NEW Child Record.
    I have 3 Tables (table1 = Parent tabel, table2 = Child Table, table12 = n:m Tabel with PK and two FK)
    The Recordsource of the Parent Form is Tabel1
    The Recordsource of the Child Form is Table2 joined with Table12.
    In my Old Access Project, Access Triggered the Insert and filled Table12 with the NEW PK of Table2.
    It seems like Access can't do that anymore....
    I'm pretty desperate and I'm sure it is just a litte thing to fix.....

  • How to achieve parent - child record insert in forms

    Guys,
    I am new to forms. I do have a requirement where I need to create one tabular block for 10 rows (parent record) and then I need to create three tabular tabs of 5 rows for detailed records (child). That means each tab can have 5 records for 1 parent row.. Thats how this parent-child structure has ONE to MANY relationships
    To achieve this requirement I created one parent block of table type (using table XX_Parent) and then I created three detailed block for each tab (Tab_A,Tab_B,Tab_C) using child table (XX_Child). For each tab while inserting the data I took one context_value column in child table. i.e. when I insert the data using Tab_A , context_value column will be A. In the same way B and C for Tab_B for Tab_C respectively. And I wrote this logic at PRE-INSERT trigger for each tab. But when I insert the data for all the tabs, it allows me to enter successfully for Tab_A only, the moment I navigate from Tab_A to enter the data intoTab_B, it throws me error like "You are passing NULL value to set context_value". I hope I make the requirement clear to you.
    I am not sure if I am following the right approach to achieve my requirement. if its not right, please suggest me right one.. and if its right please guide me resolve the error..
    Looking forward to your reply.
    Thanks
    Sunil

    Andreas,
    I had already created relations between Matster Block -Tab_A block, Master Block -Tab_B block and Master Block - Tab_C block...
    The point is all the three tabs are created using one table XX_Child only.. I used context_value A,B and C respectively so that once I query the data for XX_Child from backend, I should be in a position to figure out what data is inserted using Tab A, B and C. why I need so .. because If take my entire form in query mode and search for a master record.. then Tab_A, tab_B and Tab_C display their respective data. I hope, I make you understand.. Can you please guide me.
    Thanks
    Sunil

  • Commit Rollback for Parent & Child table

    Hi,
    I need to load data to a parent table and child table (Record by Record), i.e one record will be loaded to the parent table and the related child record will be loaded to child table.
    After first record loaded to child table, the next record will be loaded to the parent table.
    My requirement is, I should not commit the parent table before the child record is transferred (so that i can rollback if my record got failed). So I have set the parent table IKM commit option to NO. Because of this, my child record is not loaded to the correcsponding target table, its failed because the parent record is not commited.
    Do we have any possiblities to overcome this issue.
    Thanks in Advance,
    Ram Mohan T

    Cezar,
    I couldn't make the CKM options to "No Commit". When i did that i am getting the following error at step "16 - Control - CUSTOMER_DET - insert PK errors" ,
    12838 : 72000 : java.sql.SQLException: ORA-12838: cannot read/modify an object after modifying it in parallel.
    This error occurs at the CKM. so i have made all the CKM options to "commit" and IKM, LKM to "No Commit". It seems to be fine.
    Cezar,
    I have some plan for the scenario that i mentioned in the previous update (One dept id and all related employees). Please verify this,
    1) create a procedure which extracts dept_id from source tab and passes it to the scenario(in target tab) of a package.
    2) This package has the variable of dept_id, interface1 which loads data to dept and following that another procedure(2).
    3) This procedure2 will extract the emp_id that corresponds to the value of the variable dept_id. And passes this emp_id to tha scenario in target tab.
    4) This scenario is of a package which has the emp_id variable and interface2 for loading employees.
    While executing this plan, the problem is,
    1) Interface1 which loads Dept_Id is not commited (due to the KMs with commit set to "No Commit"), so that the employee records are getting loaded to the error table.
    2) I have made the interface1 KM commit option to "Default: Yes " (But still the Knowledge modules steps are No commit), but still the child records are getting loaded to error table.
    3) As per the above scenario, all these transforamtions are not taking in the same transaction. Thats the problem i believe.
    Do we have any possiblities to overcome this Cezar?
    Thanks in Advance,
    Ram Mohan T
    Edited by: T. Ram Mohan on Mar 5, 2009 11:43 AM

  • Parent child table question

    HI i have some questions which iam unclear please help me
    1) in a parent child relationship.. is it always 1-m relation from parent to child?
    2) can a parent table be on many side? i.e can a child - parent be 1- m?
    3) if i itake employee as child table and department as parent table then dept_id will be the foreigh key in employee table ...
    Now if i want to add a new employee who is not assigned to any department can i add it ?
    4) In an identifying relationship ... a child table has concatenated primary key (pk of child,pk of parent)
    should we still add any other primary key to the table....in addition to this concatenated key?
    thanks in advance
    raj

    Hi!
    1) in a parent child relationship.. is it always 1-m relation from parent to child?
    yes unless you create a unique index on the foreign key column
    2) can a parent table be on many side? i.e can a child - parent be 1- m?
    no, if you need an n-m you will need an intersection table
    e.g. employees - emp_dept - departments
    in this case the emp_dept table would contain the foreign keys of employees and departments
    3) if i itake employee as child table and department as parent table then dept_id will be the foreigh key in employee table ...
    Now if i want to add a new employee who is not assigned to any department can i add it ?
    no, you will have to insert the master first
    Best regards,
    PP

  • Parent child tables - how to maintain RI

    Here is my scenario:
    In our model, we have parent child relationship between tables.
    We are not sure how the parent tables are populated. If incremental update, it should be fine (assuming if needed rows will be inserted in the child table manually). If the tables are truncated and data is inserted again – that might be a problem since there exist relationship with child tables. What are the various options for handling such cases?
    Option1: cascade delete
    Option 2: ...?

    I'm not sure I understand the goal here...
    - Are you trying to design a data model? If so, wouldn't the business and data requirements tell you whether you need to truncate and reload the parent table or whether you can do an incremental load? It wouldn't seem to make sense to design a data model with no understanding of how the model is going to be used.
    - Are you trying to design a load process that works with an existing data model? If so, are you trying to design an incremental load? Or a load that involves a truncate and reload? Does the existing data model have foreign key constraints?
    Specifying the Oracle version and a bit of information about the application (i.e. is this an OLTP application, a data warehouse, something else) would probably also be helpful.
    Justin

  • Parent-child tables

    Hi,
    I have requirement like we have to delete a record called IT_PROG from jobs table.the jobs table have child tables employees,job_history, the employees table act as parent for employees,departments tables.How can i delete all related records using single query or single pl/sql block.
    Thanks in advance,
    Vi

    Hi,
    include it in your original table design would be the best way, with prime key, foreign key constraints and on delete cascade options.
    Other than that utilise trigger logic to coordinate your delete, but the first way is definitely the best, as triggers should be a last resort in databases....
    regards,
    Robert.

  • Update data to upper case in parent/child tables

    Hi Gurus!
    In production we have a product table and which is being reference by many tables making it parent child relationship. By mistake, we realized that last month some product were added in lower case and now we got a request to update all these product codes to upper case so that the existing code that use these tables have no impact. Appreciate if you can give some idea on how can I update the existing data in the parent table to upper case along with the child records?
    Regards
    Sri

    Are the product code that you need to update what is stored in the child tables? If so, then you would need to do it in several steps, something like:
    Identify the child tables
    SELECT table_name, constraint_name
    FROM user_constraints
    WHERE r_constraint_name = (SELECT constraint_name
                               FROM user_constraints
                               WHERE table_name = 'PRODUCT_TABLE' and
                                     constraint_type = 'P');Create the new upper case product code in product table:
    INSERT INTO product_table
    SELECT UPPER(product_code), other_columns
    FROM product_table
    WHERE product_code <> UPPER(product_code);Update the child tables to uppercase the product codes
    UPDATE child1
    SET product_code = UPPER(product_code)
    WHERE product_code <> UPPER(product_code);finally, delete the lower case product codes from product_table
    DELETE FROM product_table
    WHERE product_code <> UPPER(product_code);John

  • Why is the child table inserting first in a composite association?

    Guys and Gals,
    Studio Edition Version 11.1.1.3.0.
    This one has gotten me all day. I have a child table which is inserting before its master table, even though the relationship is defined as a composite relationship.
    Process:
    1) User adds a part with a purchase price into the Part table.
    2) Via Part-PartHistories View Link, part is inserted into PartHistories.
    3) Via BPL-BPLRows View Link, part is inserted into BPLRows along with its purchase price. The part number is part of a composite primary key (BPL,PartNumber) and is a foreign key to the Part table.
    4) Via BPL-PL View Link, and then Via PL-PLRows View Link, part is inserted into PLRows along with its purchase price. The part number is part of a composite primary key (PL,PartNumber) and is a foreign key to the Part table.
    It is #4 which gives me an integrity constraint (PCS.PRICE_BUCKETS_PARTS_FK1) violated - parent key not found error. JDev is trying to insert in the order 4,1,2,3 when it should be 1,2,3,4. The kicker is that there is a composite association between #1 and #4 which should guarantee that 1 is inserted first. If I remove #4's process, steps 1-3 run fine. If I remove the composite association, JDev inserts correctly steps 1,2,3,4.
    Why is JDev trying to insert #4 first? I do a CreateInsert on the Parts table first so the creation order is correct. Furthermore, there is a composite association defined between Parts - PLRows.
    Something is indeed fishy in Denmark.

    LovettWB,
    You talk about VOs, but composite relationships need to be defined at the EO level. If you have indeed defined the proper composite associations, this sounds like a perfect test case to submit to Oracle Support to evaluate.
    If you do have the proper associations set up and things don't work, you could try [url http://download.oracle.com/docs/cd/E17904_01/web.1111/b31974/bcadveo.htm#CEGECADE]this technique as a workaround.
    John

  • Parent-Child Table Update via Single Stored Procedure

    Uses: Oracle 9i Server via a Remote Connection with restriction, Oracle 9i client, .NET 2.0+System.Data.Oracle namespace, Delphi+BDE;
    I have an entry form which consists of a parent and a child table. I'm so keen in knowing whether there is any possibilities of updating the records via a single stored procedure? I mean if parent have a single record and corresponding to it, child have few records (more than 1 rows). I need to take the parent's value and child's value send it to the stored procedure and update it.
    Regards,

    The entry form gets the raw data from the user. So yes the data is captured front end but not updated nor processed. Once the user clicks "Save" or what ever the values are taken to the SP. In the SP the operations are done either as update or insert. Lets concentrate on Inserts only at the moment.
    I.e. there are 2 tables as:
    tbl_Payment(_PaymentID_, PaymentMode,PaymentDate, TotalPaymentValue);
    tbl_PaymentAccount(_PaymentID,AccountID_,PaymentValue);
    So the form has a top part which is bounded to the Parent Table which is "tbl_Payment" to few text boxes, and below it has a Datagrid, bounded to Child Table which is "tbl_PaymentAccount". And assume the the Single Stored Procedure as "sp_payment_addchg".
    I can pass newly entered values to the SP as:
    Command.Text = "sp_payment_addchg";
    /*so all the parent table bounded values are updated as*/
    Command.Parameter[0].value = text1.text;
    Command.Parameter[1].value = text2.text;
    and so on
    Since the DataGrid may have multiple rows, I cant figure it out how to get those rows into a single parameter.
    Regards,

  • SHOW THE PARENT CHILD TABLE RELATIONSHIP TABLE

    hi experts,
    I want show the parent child relation ship tables
    for exmple iam passing the emp table then display related child tables like dept,grade after that again child table(dept,grade) related to child relationship tables like recursive
    Regards,
    VENKAT

    Probably something like below. This may not be exactly what you are looking for, but one way to get what you are asking for.
    Only if you can give specifics, of your Input being passed and the Output, it might be possible to provide more help. But you also need to help us with your best effort on this.
    select *
      from (
            select prior table_name Child, table_name Parent
              from user_constraints
             start with constraint_name = some_constraint_name_of_Parent_Table
            connect by constraint_name = prior r_constraint_name
           ) a
    where a.child is not null;

  • Parent - child tables foreign key relation ship

    Hi All,
    we have 600 hundred tables ..i would like to print a hierarchial tree based on the foreigh key relathionship
    i tried my best but i couldnt.
    parent table
    child table 1
    childtable3
    child table 2
    and so
    Can somebody help me out with a query?
    Thanks,
    kt

    CREATE OR REPLACE FUNCTION get_child_tables (
    ptable VARCHAR2,
    powner VARCHAR2 DEFAULT 'SCOTT',
    plevel NUMBER DEFAULT 10
    RETURN stringarray
    -- -- create this ON SQL*PLUS "CREATE OR REPLACE TYPE STRINGARRAY AS TABLE OF VARCHAR2(50);"
    -- AUTHID CURRENT_USER
    PIPELINED
    AUTHOR DATE VERSION COMMENTS
    ======================================================================================
    [email protected] 26-OCT-2009 1.0 Developed to ease developers effort to find Nth level of Referential integrity
    ======================================================================================
    -- PURPOSE -> To find PARENT=> CHILD relational TABLE(S) in Oracle upto a depth max N Level.
    --SYNTAX TO USE
    SELECT * FROM TABLE( get_child_tables('DEPT','SCOTT',3)); Store this query in a file for your use
    SELECT * FROM TABLE( get_child_tables('EMPLOYEE')); Store this query in a file for your use
    -- RESULTS looks as below
    --1 => DEPT
    --2 => EMP
    --2 => EMP2
    --3 => EMP_CHILD
    --3 => EMP2_CHILD
    -- and so on
    --This can be leveraged to use in any oracle database REGION 10g having and above.
    --This FUNCTION gives formatted result of the Oracle 10g Hierarchical query result coded in the cursor
    --to find MASTER => CHILD relational TABLE(S) upto a depth max 10 Level.
    --The result of the PIPELINED function can be retrieved using Oracle new operator
    --TABLE(array name) in SQL query.
    --Due to the AUTHID CURRENT_USER compiler directive any user can use based on his/her access privileges on the database.
    --GRANT EXECUTE ON SCOTT.get_child_tables TO PUBLIC;
    --CREATE OR REPLACE PUBLIC SYNONYM get_child_tables FOR SCOTT.get_child_tables;
    IS
    atname stringarray := stringarray ();
    -- create this ON SQL*PLUS CREATE OR REPLACE TYPE STRINGARRAY AS TABLE OF VARCHAR2(50);
    vlevel NUMBER;
    vtname VARCHAR2 (50);
    nindex NUMBER := 0;
    bprocessed BOOLEAN := FALSE;
    CURSOR c1 (powner_in IN VARCHAR2, ptable_in VARCHAR2, plevel_in NUMBER)
    IS
    SELECT LEVEL, LPAD (' ', (LEVEL - 1) * 2, ' ') || pt AS "TNAME"
    FROM (SELECT a.owner w1, a.table_name pt, a.constraint_name c1,
    a.r_constraint_name r1, b.owner w2, b.table_name ct,
    b.constraint_name c2, b.r_constraint_name r2
    FROM all_constraints a, all_constraints b
    WHERE a.constraint_name = b.r_constraint_name(+)
    AND a.owner = b.owner(+)
    AND a.owner =
    UPPER (powner)
    -- Change Owner here while testing
    --AND A.r_constraint_name IS NULL
    AND a.constraint_type IN ('P', 'R')) v1
    START WITH pt =
    UPPER
    (ptable)
    -- Change your master table here while testing the QUERY
    CONNECT BY PRIOR ct = pt AND LEVEL <= plevel;
    -- Change lavel here while testing
    BEGIN
    atname.EXTEND;
    atname (1) := 'NOTHING';
    OPEN c1 (powner, ptable, plevel);
    LOOP
    bprocessed := FALSE;
    FETCH c1
    INTO vlevel, vtname;
    IF nindex > 1 AND atname (atname.LAST - 1) = vtname
    THEN
    --DBMS_OUTPUT.PUT_LINE('2 ==== vtname  ' ||vtname || '   '|| atname.count|| '   '||atname.last ||  '   '||atname( atname.last-1));
    bprocessed := TRUE;
    END IF;
    IF NOT bprocessed
    THEN
    nindex := nindex + 1;
    atname.EXTEND;
    atname (nindex) := vtname;
    PIPE ROW (vlevel || ' => ' || vtname);
    DBMS_OUTPUT.put_line ( ' **** nindex - atname( nindex) '
    || nindex
    || ' - '
    || atname (nindex)
    DLOG('ADDING ',vTname); A LOGGING ATONOMUS PROCEDURE FOR DEBUG PURPOSE
    END IF;
    EXIT WHEN c1%NOTFOUND;
    END LOOP;
    CLOSE c1;
    FOR i IN 1 .. atname.COUNT
    LOOP
    DBMS_OUTPUT.PUT_LINE('atname (i) ' ||atname (i));
    END LOOP;
    RETURN;
    EXCEPTION
    WHEN no_data_needed
    THEN -- THIS EXCEPTION HAS TO BE THERE TO GET THE FUCTION WORKABLE
    DBMS_OUTPUT.put_line (SQLERRM);
    RETURN;
    END get_child_tables;
    /

  • Parent - child table issue wrt to count - SQL question

    I have a scenario:
    There are 2 tables (parent and child). lets say, case summary table and task level dimension table.
    for every case id in case summary table, there would be multiple tasks in task level dim table with a flag indicator set to 1 for all tasks.
    but while counting the number of cases active with flag indicator 1 (ofcourse when joining case summary table with task dimension table), for a case id only 1 instance of task needs to be accounted (even though it has more than one task , for counting active cases, the flag ind corresponding to a task in a case if set to 1 , then the case is considered active)..but while joining and taking count of case ids with flag indicator as 1, you get the count of every task row of a case which is incorrect logically. how to discard the rest of child records of a case in child table (task dimension table)?
    I am not sure how to achieve this in sql query
    Kindly help!
    Case summary table
    case id, busininess_unit, agent_name
    1001, admin, Ram
    1002, Finance, Sam
    task table
    case id, task_id,task_name, flag_indicator
    1001, 1, 'New', 1
    1001,2, 'Open',1
    1001,3,'In progress',1
    1002, 4, 'New', 1
    (In fact task_id is not a big deal... even you can assume task id doesn't exist..only task name ... )
    now my question... if my query should get the current active cases (ind=1); as per above it should essentially give 2... but my query gives me 4..you know the reason why.. but how do i get the correct count?
    Thanks!

    may be you need just this:
    select count(distinct case_id) from task
    where indicator = 1;
    If this is not what you are looking for, please elaborate and tell us the expected output and rest of the details as mentioned in FAQ Re: 2. How do I ask a question on the forums?:

Maybe you are looking for