Self-housekeeping tables?

Hi,
I know, housekeeping is not so easy. But there are cases when I could image very simple delete-rules, e.g. for a logging-table.
Then it would be a cool feature to have something like:
- remove records from table older than 10 days (supposed the table has created_at-field)
as a builtin-feature of the database.
Is something possible with oracle?
Thomas

The options could be
a. Partitioned Table with scheduled code to DROP older partitions
b. Materialized View that is created as a sliding window -- but this still doesn't purge records from the source table
c. Purge Job
However, in all these cases you still have to write the code to purge/drop older rows. I did think of Interval Partitioning and Reference Partitioning but I am not aware of any automated way ("Oracle-managed") way to purge older partitions.
The ILM Assistant can be use to configure management of large data sets.
See the documentation on "Using Partitioning for Information Lifecycle Management"
at http://download.oracle.com/docs/cd/E11882_01/server.112/e16541/part_lifecycle.htm#CACECAFB
If you are talking of "small" tables (e.g. "this table always need to retain only 1 weeks data and the total volume is about 7000 rows in a week") you'd still have to write your own code.
Hemant K Chitale

Similar Messages

  • Best practice: self referencing table

    Hallo,
    I want to load a self referencing table to my enterprise area in the dwh. I am not sure how to do this. What if a record references to another record which is inserted later in the same etl process? There is now way to sort, because it is possible that record a references to record b and record b references to record a. Disabling the fk constraint is not a good idea, because this doesn't prevent that invalid references will be loaded? I am thinking of building two mappings, one without the self referencing column and the other only with it, but that would cause approx. twice as much running time. Any other solutions?
    Regards,
    Torsten

    Mind sharing the solution? Would be interested to hear your solution (high level).
    Jean-Pierre

  • Resolve self-reference table by alias tables in detail

    Hello Gurus,
            can you tell me how to resolve self-reference table by alias tables in detail?
    Many thanks.

    Hello, for the following step 3, I don't understand, will you please give me some explanation for step 3?
    Save your Staff universe, and test the results in Web Intelligence Rich Client as follows:
    1. Run a query using Manager and Employee. Add a count on both columns.
    2. Add a query with only the Manager object. Add a count. Is this the correct value?
    3. Open your Staff universe in Universe Designer and edit the Manager object. To ensure
    that the data is restricted to only manager data, use the Tables button. Select the
    EMPLOYEE table, to force the object to use the join between the table and restrict the
    data.
    4. Test the result, creating a new query with only the Manager object. It returns the correct
    number of managers.
    5. Edit the query and add Employee. Run and display the count. There are 26 rows. Why?
    The join restricts the data to look only for employees that have managers. However, there
    is a manager that does not have a manager, and is now excluded.
    6. Open your Staff universe in Universe Designer and add an outer join on the MANAGER
    table side.
    7. Save the changes and test the results in Web Intelligence Rich Client.

  • Self Referencing Tables...

    I have a self-referencing table (a Topic can be a response to another Topic) and read one of Frank Nimphius' blogs on this subject, posted on the ADF board for advise. As a result I created the read-only ViewObject to set up this tree relationship and set it to be exposed to the App Module.
    Do I need to do more to it than that for JHeadstart to generate the right page defs? Any advise on setting this up cleanly? My user interface must present a page in which users can post new Topics, view topics in a heirarchy (response thread, like in this forum) and respond to Topics or responses. A response is a Topic that references another (parent) Topic. I have to believe this has been done before a million times but am not sure myself how to do it.
    Thanks!

    Steve,
    I've read the section and am getting this error:
    (oracle.jbo.SQLStmtException) JBO-27122: SQL error during statement preparation. Statement: SELECT Topic.SUBJECT, Topic.ROW_ID, Status.STATUS_CHOICE, Status.ROW_ID AS ROW_ID11, Topic.CREATED_BY, Topic.CREATION_DATE, Response.SUBJECT AS SUBJECT1, Response.CREATION_DATE AS CREATION_DATE1, Response.ROW_ID AS ROW_ID12, Response.CREATED_BY AS CREATED_BY1 FROM TOPIC Topic, RESPONSE Response, STATUS Status WHERE (Topic.ROW_ID = Response.MASTER_ID (+)) AND (Topic.TOPIC_STATUS_ID = Status.ROW_ID) CONNECT BY PRIOR Topic.ROW_ID = Response.MASTER_ID (+) OR Response.ROW_ID = Response.MASTER_ID (+) ORDER BY SUBJECT,CREATION_DATE1
    ----- LEVEL 1: DETAIL 0 -----
    (java.sql.SQLException) ORA-01436: CONNECT BY loop in user data
    I have a table called Topic with a Pk called ROW_ID and another table called Response with a Pk called ROW_ID and an Fk called MASTER_ID. A Topic can have many Responses and a Response can also have many Responses. The parent ID could point to either a Topic or a Response. There's no limit on how many levels this can continue. There's a Status table also from which I want to show the text value of the Status for the Topic row (not the Status ROW_ID)
    I have a View Object including entities: Topic, Response & Status
    I tried the SQL query as:
    (Topic.ROW_ID = Response.MASTER_ID (+)) AND (Topic.TOPIC_STATUS_ID = Status.ROW_ID) CONNECT BY PRIOR Topic.ROW_ID = Response.MASTER_ID (+) OR Response.ROW_ID = Response.MASTER_ID (+)
    Hoping to have this result:
    Topic A
    -Response A (to Topic A)
    --Response B (to A)
    ---Response C (to B)
    -Response D (to Topic A)
    Topic B
    Topic C
    What am I doing wrong?
    Is there a guide that explains better using JHeadstart with JDeveloper (rather than Oracle Designer, which we don't use)? The developer's guide for JHeadstart is hard to translate for use with JDeveloper...
    Thanks!!

  • How to build query to get tree architecture of self referencing table

    Dear all,
    I have the following table design :
    This is a self referencing table representing a set of SubCategories which can have parent sub categories or not. I did not show here the Category table.
    If the Subcategory has the ParentSubCategory ID = null, then this is a root subcategory otherwise it is a child of a parent sub category.
    What I am looking for is the easy way to display the structure level by ProductCategoryID ?
    Thanks for helps

    you can use a recursive logic based on CTE for that
    something like this would be enough
    ;WITH ProdSubCat_Hiererchy
    AS
    SELECT psc.ProductSubCategoryID,c.CategoryName,psc.ParentSubCategoryID, psc.Name,CAST(psc.Name AS varchar(max)) AS [Path],1 AS [level]
    FROM ProductSubCategory psc
    INNER JOIN Category c
    ON c.CategoryID = psc.ProductCategoryID
    WHERE psc.ParentSubCategoryID IS NULL
    UNION ALL
    SELECT psc.ProductSubCategoryID,c.CategoryName,psc.ParentSubCategoryID, psc.Name,CAST(psch.[Path] + '/' + psc.Name AS varchar(max)) AS [Path],psch.[level] + 1
    FROM ProductSubCategory psc
    INNER JOIN Category c
    ON c.CategoryID = psc.ProductCategoryID
    INNER JOIN ProdSubCat_Hiererchy psch
    ON psch.ProductSubCategoryID = psc.ParentSubCategoryID
    SELECT *
    FROM ProdSubCat_Hiererchy
    ORDER BY LEFT([Path],CHARINDEX('/',[Path]+'/')-1),[Level]
    OPTION (MAXRECURSION 0)
    Please Mark This As Answer if it helps to solve the issue Visakh ---------------------------- http://visakhm.blogspot.com/ https://www.facebook.com/VmBlogs

  • JPA: How to initialise an entity for a self-referencing table?

    I am working on a project that requires a self-referencing table:
    mysql> show create table attributes\G
    *************************** 1. row ***************************
           Table: attributes
    Create Table: CREATE TABLE `attributes` (
      `id` int(11) NOT NULL AUTO_INCREMENT,
      `parent` int(11) DEFAULT NULL,
      `type` int(11) DEFAULT NULL,
      `name` varchar(128) DEFAULT NULL,
      PRIMARY KEY (`id`),
      KEY `parent` (`parent`),
      KEY `type` (`type`),
      CONSTRAINT `attributes_ibfk_1` FOREIGN KEY (`parent`) REFERENCES `attributes` (`id`),
      CONSTRAINT `attributes_ibfk_2` FOREIGN KEY (`type`) REFERENCES `attributes` (`id`)
    ) ENGINE=InnoDB AUTO_INCREMENT=26 DEFAULT CHARSET=latin1
    I used NetBeans to generate an entity class from the table:
    @Entity
    @Table(name = "attributes")
    @XmlRootElement
    @NamedQueries({
        @NamedQuery(name = "Attributes.findAll", query = "SELECT a FROM Attributes a"),
        @NamedQuery(name = "Attributes.findById", query = "SELECT a FROM Attributes a WHERE a.id = :id"),
        @NamedQuery(name = "Attributes.findByName", query = "SELECT a FROM Attributes a WHERE a.name = :name")})
    public class Attributes implements Serializable {
        private static final long serialVersionUID = 1L;
        @Id
        @GeneratedValue(strategy = GenerationType.IDENTITY)
        @Basic(optional = false)
        @Column(name = "id")
        private Integer id;
        @Size(max = 128)
        @Column(name = "name")
        private String name;
        @OneToMany(mappedBy = "parent")
        private Collection<Attributes> attributesCollection;
        @JoinColumn(name = "parent", referencedColumnName = "id")
        @ManyToOne
        private Attributes parent;
        @OneToMany(mappedBy = "type")
        private Collection<Attributes> attributesCollection1;
        @JoinColumn(name = "type", referencedColumnName = "id")
        @ManyToOne
        private Attributes type;
        @OneToMany(cascade = CascadeType.ALL, mappedBy = "attributes")
        private Collection<ItemAttributes> itemAttributesCollection;
        @OneToMany(mappedBy = "ivalue")
        private Collection<ItemAttributes> itemAttributesCollection1;
    But how can I write a constructor for this entity? The auto-generated code gets around the issue by doing nothing; the constructor is empty. I can't help thinking that if I set the parent and type references to anything with new Attributes(), then it will recurse out of control. What else can/shall I do? I know how to rewrite it to not use the entity relations, but I'd prefer to make it work.

    Cymae wrote:
    I don't want to call the hash table creation method because from what i understand about interfaces the idea is that your main method doesnt know the table is actually a hash table...is that right?That's not exactly the idea. The idea to use the interface as the type instead of the implementation, is that your class probably doesn't need to know the full type. This makes it easy to change the implementation of the interface if needed. However, somebody at some point has to create the concrete object, a HashTable.
    Basically, an interface describes a behavior, and a class that implements an interface decides how to actually perform this behavior. It is obviously impossible to perform the behavior if you are not told how to perform it.
    Table table = new HashTable() is the correct way to do it. This means that if you ever need you Table implementation to change, the only thing you need to change in your whole class is this line. For example you might want Table table = new FileTable().

  • Query output help: Display self-referencing table

    Hello,
    I'm trying to display in a cfoutput a self-referencing table.
    I'll start by showing some of the data in the table.
    There are only 3 columns, pl_id (auto increment id pri-key),
    pl_name and pl_parent_id (it's 0 if it's a parent, otherwise it's
    the pl_id value for the parent).
    pl_id pl_name pl_parent_id
    1 Country 0
    2 Food 0
    3 US 1
    4 Japan 1
    5 Hamburger 2
    6 Idaho 3
    7 Florida 3
    8 Cheese 2
    What I'm trying to output is something like this:
    Country - US - Idaho (3 levels here) or
    Country - US - Florida (or if there are only 2 levels like
    the next line)
    Food - Cheese
    I've tried using a cfoutput with a cfloop as well as grouping
    but not having any luck. Could someone clear my clouded head on
    this one?
    thanks much,
    Joe
    ps. Adobe should really use a fixed width font for these
    forums, it's impossible to line up table info!

    JoeNH2k wrote:
    > It would be nice if it were that easy, I (of course)
    tried that. The sort order
    > of the query doesn't matter. The data is not sorted once
    the function runs. The
    > sort has to come after the select box is populated by
    the function. I need to
    > get the data at this point and sort it, probably somehow
    creating a structure
    > or array from this data and sorting that(?).
    >
    <cfset myArr = ArrayNew(1)>
    <cfloop query="qryGetAll">
    <cfset temp = ArrayAppend(myArr,
    "#getNameWithParent(pl_id)#")>
    </cfloop>
    <cfset ArraySort(myArr, "textnocase", "asc")>
    <cfset myList = ArrayToList(myArr, ",")>
    then loop through myList to populate your <select>...
    how about that?
    Azadi Saryev
    Sabai-dee.com
    Vientiane, Laos
    http://www.sabai-dee.com

  • Self referencing table many to many relationship

    I am in a bit of a logic pickle, and I was wondering if someone could help me out.
    I have a table in a database I am designing called document, it holds information on surprisingly on documents in our DMS.
    I want to create the notion that a document can have multiple related documents, and those documents can be the related documents for many documents.
    So it is a self referencing table, I have done these before so no big deal, but this time is a many to many relation, it wasnt before.
    Maybe something like:
    document
    docid (pk)
    related_doc
    docid (pk) (fk to document.docid)
    related_docid (pk) fk to document.docid)
    Does anyone have any experience with this or any advise I might find sueful?
    Thanks!

    A junction table can be used to resolve a many-to-many relationship as is in your example. There are two PK/FK relationships between document and related_document table. This will prevent denormalization of data.
    The other option could be to have just one table with two columns (parent_doc_id and child_doc_id) and have a PK constraint on both the columns - just like bill-of-materials.
    But I think the approach you have in your posting will work well.
    Shakti
    http://www.impact-sol.com
    Developers of Guggi Oracle - Tool for DBAs and Developers

  • Self referencing table and SQL statement

    In my database, I have a self-referencing table, the table itself is for projects, and it allows users to get a hierarchical view of the company.
    Here is the SQL (modifier is the term we use for project code, BBCI is the top project)
    SELECT
    modifier, modifierDescription, level
    FROM
    modifier
    WHERE
    level <= 2
    CONNECT BY PRIOR
    modifier = parentModifier
    START WITH modifier = 'BBCI'
    ORDER BY level
    That perticular query gets the first two levels in the structure. I use this information to produce a tree structure in a web app.
    But users have requested it would be good if in the tree structure is showed an + or - depending on whether there were anymore children under each parent, or better still the number of children under it, for example
    BBCI
    + BBCI_CHILD
    + BBCI_CHILD2
    - BBCI_CHILD3
    or
    BBCI
    + BBCI_CHILD (3 projects underneath)
    + BBCI_CHILD2 (2 projects underneath)
    - BBCI_CHILD3 (0 projects underneath)
    I am really stumped on this issue, and I am sure there is a way to do this in the web app, so for example do a query for each child node to see how many child nodes are underneath, but I figure it would be a lot tidier and faster if I could do it from a single SQL statement. Unfortunately I have tried to do this and am very much stuck.
    If you need more information please let me know
    Thanks!
    Jon

    You may be able to do this using analytical functions but it depends on the Oracle version you are using. It can also be done with standard SQL - you just need to count the number of child rows for each modifier/project first and supply that list as an in-line view:
    SELECT decode(modifier,'X',null,decode(child_rows,null,'-','+')),
    m.modifier,
    decode(modifier,'X',null,'('||nvl(cq.child_rows,0)||' projects underneath)')
    FROM modifier m,
    (select parentModifier,
         count(parentModifier) child_rows
    from modifier
    where parentModifier is not null
    group by parentModifier) cq
    WHERE m.modifier=cq.parentModifier(+)
    AND level <= 2
    CONNECT BY PRIOR
         m.modifier = m.parentModifier
    START WITH modifier = 'X'
    ORDER BY level, modifier;
    which gives you something like...
    D MODIFIER DECODE(MODIFIER,'X',NULL
    X
    - Y1 (0 projects underneath)
    + Y2 (2 projects underneath)
    + Y3 (3 projects underneath)
    The decode stuff is just to show you the result, you can format the output in your calling code. Just extend the columns to include everything you want, modifierDescription etc..
    Hope this helps.

  • Self referencing table and contraint

    Hi,
    I have a self referencing table, used to store information on projects in an organization. There is a pimary key (modifier) and a foreign key to the modifier field (parentModifier)
    Note: (modifier = project in the organization)
    Basically, the parentModifier cannot be equal to the modifier in the same table, or equal to any of its children, otehrwise you get wierd recursive relationships. Its like saying you cannot be your own father, or one of your children cannot be your father. To get a list of the modifiers the parentModifier cannot be, the following statement can be used:
    select
    modifier
    from
    modifier
    where
    modifier = 'A'
    and
    level >= 1
    connect by prior
    modifier = parentModifier
    start with
    modifier = 'A'
    order by
    level;
    So, now, I guess the way to do this is perform that query in a trigger before each row is being updated, so the pseudo code would be something like:
    BEFORE UPDATE ON modifier
    FOR EACH ROW
    DECLARE
    modifierToChange varchar2(255);
    modifierList ???;
    BEGIN
    select
    modifier
    into
    modifierList
    from
    modifier
    where
    modifier = 'A'
    and
    level >= 1
    connect by prior
    modifier = parentModifier
    start with
    modifier = 'A'
    order by
    level;
    if modifierToChange in modifierList
    return error
    else
    execute query
    end if
    END
    As you can see my PL/SQL is limitied. At the moment I can handle this at the application layer (in php), but if the admin going to SQL Plus and starts to fiddle, they can easy break the system, by setting an invalid relationship.
    I was wondeirng, if anyone could give me some help or advice, it would be fantastic,
    Thanks!

    Having a unique key on mod_id would be enough to make sure the same element is not in the structure more than once. By allowing it to happed you will have all the descendants of the dup element following it when you walk the tree.
    Let's say this is the intended behavior.
    Consider the following test scenario:
    create table modifier (
      mod_id varchar2(10),
      parent_mod_id varchar2(10)
    insert into modifier (mod_id, parent_mod_id) values ('a', null);
    insert into modifier (mod_id, parent_mod_id) values ('aa', 'a');
    insert into modifier (mod_id, parent_mod_id) values ('ab', 'a');
    insert into modifier (mod_id, parent_mod_id) values ('ac', 'a');
    insert into modifier (mod_id, parent_mod_id) values ('aaa', 'aa');
    insert into modifier (mod_id, parent_mod_id) values ('aab', 'aa');
    insert into modifier (mod_id, parent_mod_id) values ('aac', 'aa');
    insert into modifier (mod_id, parent_mod_id) values ('aba', 'ab');
    insert into modifier (mod_id, parent_mod_id) values ('abb', 'ab');
    insert into modifier (mod_id, parent_mod_id) values ('abc', 'ab');
    insert into modifier (mod_id, parent_mod_id) values ('aca', 'ac');
    insert into modifier (mod_id, parent_mod_id) values ('acb', 'ac');
    insert into modifier (mod_id, parent_mod_id) values ('acc', 'ac');
    insert into modifier (mod_id, parent_mod_id) values ('b', null);
    insert into modifier (mod_id, parent_mod_id) values ('ba', 'b');
    insert into modifier (mod_id, parent_mod_id) values ('bb', 'b');
    insert into modifier (mod_id, parent_mod_id) values ('bc', 'b');
    insert into modifier (mod_id, parent_mod_id) values ('baa', 'ba');
    insert into modifier (mod_id, parent_mod_id) values ('bab', 'ba');
    insert into modifier (mod_id, parent_mod_id) values ('bac', 'ba');
    insert into modifier (mod_id, parent_mod_id) values ('bba', 'bb');
    insert into modifier (mod_id, parent_mod_id) values ('bbb', 'bb');
    insert into modifier (mod_id, parent_mod_id) values ('bbc', 'bb');
    insert into modifier (mod_id, parent_mod_id) values ('bca', 'bc');
    insert into modifier (mod_id, parent_mod_id) values ('bcb', 'bc');
    insert into modifier (mod_id, parent_mod_id) values ('bcc', 'bc');
    commit;
    SQL> select lpad(' ', 2 * (level - 1)) || mod_id item
      2    from modifier
      3   start with parent_mod_id is null
      4  connect by prior mod_id = parent_mod_id;
    ITEM
    a
      aa
        aaa
        aab
        aac
      ab
        aba
        abb
        abc
      ac
        aca
        acb
        acc
    b
      ba
        baa
        bab
        bac
      bb
        bba
        bbb
        bbc
      bc
        bca
        bcb
        bcc
    26 rows selected
    Create a function to verify if a mod_id already is parent_mod_id's ascendant or descendant:
    create or replace function exists_in_parents_branch
      i_mod_id in varchar2
    ,i_parent_mod_id in varchar2
    ) return boolean is
      pragma autonomous_transaction;
      v_dummy varchar2(10);
    begin
      select mod_id
        into v_dummy
        from (select mod_id
                from modifier
               where mod_id = i_mod_id
              connect by prior mod_id = parent_mod_id
               start with mod_id = i_parent_mod_id
              union
              select mod_id
                from modifier
               where mod_id = i_mod_id
              connect by prior parent_mod_id = mod_id
               start with mod_id = i_parent_mod_id);
      return true;
    exception
      when no_data_found then
        return false;
    end exists_in_parents_branch;
    Create a trigger that calls the function above for every insert and update
    create or replace trigger biu_modifier
    before insert or update on modifier
    for each row
    begin
      if exists_in_parents_branch(:new.mod_id, :new.parent_mod_id) then
        raise_application_error(-20000, 'Cannot insert or update because of recursive relationship.');
      end if;
    end biu_modifier;
    You are all set.
    Here is a statement that should fail:
    SQL> insert into modifier (mod_id, parent_mod_id) values ('bcc', 'b');
    insert into modifier (mod_id, parent_mod_id) values ('bcc', 'b')
    ERROR at line 1:
    ORA-20000: Cannot insert or update because of recursive relationship.
    ORA-06512: at "RC.BIU_MODIFIER", line 3
    ORA-04088: error during execution of trigger 'RC.BIU_MODIFIER'
    Here is a statement that should succeed:
    SQL> insert into modifier (mod_id, parent_mod_id) values ('aaaa','aaa');
    1 row created.

  • Self leveling Table

    Hello Everybody,
    We are worknig on a Self levelling table. Basically I am trying to build a table which will have a fixed leg in the middle connected with the ball joint to the table top so it will have 2 degree of freedom. This table is 12" X 18" and it will have 2 degree of freedom. The others legs will be connected in a right angle of each other. These two legs will be controlled by dc motor  linear actuator and they will try to keep the surface of the table balanced when the platform of the table will be tilted by +/- 5cm.
    This incline/tilt will be detected by inclinometer and I am hoping that some how I can interface inclinometer to LabView, and then the output should go to HB-25 (H-Bridge circuit) to drive the linear dc motor actuator.
    I am hoping if you could help me finding the right hardware for this job. Currently our university has NI USB-6251, do you think this will be ok for our project if so then what kind of drivers or interface do we need so we can get the output from the inclinometer to computer and what do i need to interface with dc motor linear actuator so it can respond to that changes to make the table level. Thanks in advance.
    Message Edited by Rajb on 09-29-2007 02:27 PM
    Attachments:
    self.jpg ‏17 KB

    Hi Rajb,
    You could use your USB-6251 to control the HB-25 with Pulse Width Modulation (PWM), as long as the current requirement is within the specification of the 6251. This however, would be software timed control, meaning it would be nondeterministic and you can't guarantee accurate control. I roughly estimate the latency between reading the inclinometer input and writing a PWM signal to the motors would be anywhere from 3-10 ms. That number comes from some rough tests I did on my computer, not from the user manual, so it is not a guaranteed statistic.  However, it does serve to give you a basis for judgment on whether your 6251 will be sufficient as a controller. If that is insufficient, you will want to use a cRIO chassis, which is much faster, and deterministic.  You would still control your motors with PWM through the H-Bridge and whatever software algorithm you write, but it would be on a Real Time target.
    I hope this helps!
    Maclean G.
    Applications Engineering
    National Instruments

  • ORA-02291 during MERGE on self-referenced table

    Hello,
    I encountered error ORA-02291 when I tried to use MERGE statement on the table with "self-referenced" foreign key. Using the foreign key deferrable did not help. The only one thing, which helped me, was using errorlog table. See the demonstration:
    Working as common user:
    SQL> CONNECT scott/tiger
    First of all, I create table and (not deferrable) constraints:
    CREATE TABLE fkv (
         id NUMBER(1) CONSTRAINT nn_fkv_id NOT NULL,
         parent_id NUMBER(1) CONSTRAINT nn_fkv_paid NOT NULL
    ALTER TABLE fkv ADD CONSTRAINT pk_fkv_id PRIMARY KEY (id);
    ALTER TABLE fkv ADD CONSTRAINT fk_fkv_paid FOREIGN KEY (parent_id) REFERENCES fkv(ID) NOT DEFERRABLE;
    INSERT is working well:
    INSERT INTO fkv (
         id,
         parent_id
    SELECT
    1,
    1
    FROM
    DUAL;
    COMMIT;
    1 rows inserted.
    commited.
    MERGE statement using UPDATE branch is working well too:
    MERGE INTO fkv USING (
    SELECT
    1 AS ID,
    1 AS PARENT_ID
    FROM
    DUAL
    ) a
    ON (
    fkv.id = a.id
    WHEN MATCHED THEN
    UPDATE SET
    fkv.parent_id = a.parent_id
    WHERE
    A.ID IS NOT NULL
    DELETE WHERE a.id IS NULL
    WHEN NOT MATCHED THEN
    INSERT (
    ID,
    parent_id
    VALUES (
    A.ID,
    A.PARENT_ID);
    COMMIT;                                        
    1 rows merged.
    commited.
    And now is coming the strange behaviour:
    MERGE INTO fkv USING (
    SELECT
    2 AS id,
    2 AS PARENT_ID
    FROM
    DUAL
    ) a
    ON (
    fkv.id = a.id
    WHEN MATCHED THEN
    UPDATE SET
    fkv.parent_id = a.parent_id
    WHERE
    A.ID IS NOT NULL
    DELETE WHERE a.id IS NULL
    WHEN NOT MATCHED THEN
    INSERT (
    ID,
    parent_id
    VALUES (
    A.ID,
    A.PARENT_ID);
    SQL Error: ORA-02291: integrity constraint (SCOTT.FK_FKV_PAID) violated - parent key not found
    ROLLBACK;
    rollback complete.
    Ok, even it is not a good solution, I try deferrable constraint:
    ALTER TABLE fkv DROP CONSTRAINT fk_fkv_paid;
    ALTER TABLE fkv ADD CONSTRAINT fk_fkv_paid FOREIGN KEY (parent_id) REFERENCES fkv(id) DEFERRABLE INITIALLY DEFERRED;
    table FKV altered.
    table FKV altered.
    MERGE INTO fkv USING (
    SELECT
    2 AS id,
    2 AS PARENT_ID
    FROM
    DUAL
    ) a
    ON (
    fkv.id = a.id
    WHEN MATCHED THEN
    UPDATE SET
    fkv.parent_id = a.parent_id
    WHERE
    A.ID IS NOT NULL
    DELETE WHERE a.id IS NULL
    WHEN NOT MATCHED THEN
    INSERT (
    ID,
    parent_id
    VALUES (
    A.ID,
    A.PARENT_ID);
    1 rows merged.
    COMMIT;
    SQL Error: ORA-02091: transaction rolled back
    ORA-02291: integrity constraint (SCOTT.FK_FKV_PAID) violated - parent key not found
    ... deffered constraint did not help :-(
    Let's try another way - errorlog table; for the first with the not deferrable constraint again:
    ALTER TABLE fkv DROP CONSTRAINT fk_fkv_paid;
    ALTER TABLE fkv ADD CONSTRAINT fk_fkv_paid FOREIGN KEY (parent_id) REFERENCES fkv(ID) NOT DEFERRABLE;
    table FKV altered.
    table FKV altered.
    BEGIN
    sys.dbms_errlog.create_error_log (
    dml_table_name => 'FKV',
    err_log_table_name => 'ERR$_FKV'
    END;
    anonymous block completed
    Toys are prepared, let's start with error logging:
    MERGE INTO fkv USING (
    SELECT
    2 AS id,
    2 AS PARENT_ID
    FROM
    DUAL
    ) a
    ON (
    fkv.id = a.id
    WHEN MATCHED THEN
    UPDATE SET
    fkv.parent_id = a.parent_id
    WHERE
    A.ID IS NOT NULL
    DELETE WHERE a.id IS NULL
    WHEN NOT MATCHED THEN
    INSERT (
    ID,
    parent_id
    VALUES (
    A.ID,
    A.PARENT_ID)
    LOG ERRORS INTO err$_fkv;
    1 rows merged.
    Cannot belive, running SELECT for confirmation:
    SELECT * FROM err$_fkv;                    
    SELECT * FROM fkv;
    no rows selected
    ID PARENT_ID
    1 1
    2 2
    Ok, COMMIT:
    COMMIT;
    commited.
    SELECT for confirmation again:
    SELECT * FROM err$_fkv;                    
    SELECT * FROM fkv;
    no rows selected
    ID PARENT_ID
    1 1
    2 2
    Using deffered constraint and error logging is working well too.
    Metalink and Google did not help me. I am using databases 10.2.0.5 and 11.2.0.3.
    Has somebody encountered this problem too or have I missed something?
    Thank you
    D.

    drop table fkv;
    CREATE TABLE fkv (
    id NUMBER(1) CONSTRAINT nn_fkv_id NOT NULL,
    parent_id NUMBER(1) CONSTRAINT nn_fkv_paid NOT NULL
    CREATE INDEX PK_FKV_ID ON FKV(ID);
    ALTER TABLE fkv ADD CONSTRAINT pk_fkv_id PRIMARY KEY (id);
    ALTER TABLE FKV ADD CONSTRAINT FK_FKV_PAID FOREIGN KEY (PARENT_ID) REFERENCES FKV(ID);Now run your MERGE statement and it works with non deferrable constraints.
    Personally, I would contact support about this before depending on it in production.
    P.S. I was not able to reproduce your findings that dropping and re-adding the constraints changes things. I suspect that when you dropped the constraint the index was NOT dropped, so you kept a non-unique index.
    Try again using ALTER TABLE FKV DROP CONSTRAINT PK_FKV_ID drop index;

  • Foreign Key Constraint Failure on Self-Referencing Table

    In a recent data deletion project, I ran into a problem where Oracle allowed for a record (the parent) to be deleted when there still existed a child record in the same table which referred to the parent.
    An abbreviated version of the table is as follows:
    create table test (
    template_id number not null,
    customer_id number null,
    parent_id number null,
    constraint pk_test primary key (template_id),
    constraint r_parent foreign key (parent_id) references test (template_id));
    The parent and child records are as follows:
    Parent: template_id = 100, customer_id = 200, parent_id = null
    Child: template_id = 101, customer_id = null, parent_id = 100
    Records were deleted from this table using:
    DELETE FROM test WHERE customer_id = 200;
    When this statement is executed, is it being executed as part of 155 delete statements using PL/SQL, and tens of thousands of records from 155 tables are being deleted. These delete statements have been ordered taking into account foreign key constraints. All 155 statements are being deleted in a single transaction. The delete statement above was the 23rd statement of the set to be executed. I would have expected when this delete statement was executed, an error would have been thrown. However, all 155 delete statements successfully complete, and after committing the results, the child record above still exists in the DB as an orphan. I also tried executing the first 23 statements manually in SQL*Plus (still one transaction), and the problem still occurs: the parent is deleted and the child is orphaned.
    If I execute the very simple example above, I do indeed get an referential constraint error.
    Has anyone ever encountered this situation? And does anyone have any ideas how to go about troubleshooting this problem. We need to know the cause of this, as we have a small handful of table with a similar self-referential foreign key constraint set-up.
    Thank you very much in advance,
    Mark

    First of all, the very simple example that I outlined above I have already tried and it worked: when I attempted to delete the parent a referential integrity error was thrown as one would expect. This small example was my test case to see if I could reproduce what I'm seeing in our application in a more manageable and demonstrable example. But as it worked, I'm still perplexed in reconciling the differences between what I'm seeing in our application (which I can't demonstrate in this help group) and the test case. When I used the test case in my first posting in this thread, I used it to help describe the problem I'm encountered, even though that small example works.
    Below is more of the table you've asked for.
    OWNER           CONSTRAINT_NAME          CONSTRAINT_TYPE     TABLE_NAME     SEARCH_CONDITION     R_OWNER            R_CONSTRAINT_NAME     DELETE_RULE     STATUS          DEFERRABLE            DEFERRED         VALIDATED     GENERATED     BAD     RELY     LAST_CHANGE           INDEX_OWNER  INDEX_NAME       INVALID     VIEW_RELATED
    "DOCPADMIN"     "R_TEMPLATE_PARENT"     "R"             "DCR_TEMPLATE"      (null)                  "DOCPADMIN"     "XPKDCR_TEMPLATE"     "NO ACTION"  "ENABLED"   "NOT DEFERRABLE"    "IMMEDIATE"  "VALIDATED"      "USER NAME"     (null)     (null)     "2010-01-13 19:01:21"     (null)        (null)         (null)       (null)
    "DOCPADMIN"     "XPKDCR_TEMPLATE"       "P"             "DCR_TEMPLATE"      (null)                       (null)     (null)                      (null)          "ENABLED"     "NOT DEFERRABLE"    "IMMEDIATE"      "VALIDATED"     "USER NAME"     (null)     (null)     "2010-01-13 15:48:31"     (null)     "XPKDCR_TEMPLATE"   (null)     (null)Overall, I haven't said that Oracle's FK mechanism is broken. What I've said is that I've got a situation that I'm trying to understand. My first attempt at my test case didn't work because the test case worked as it should. I'm trying to figure out another course of action to try and figure this situation out.

  • Oracle 10g - Insert value into a self-created table in stored proc

    Hi all,
    Say I'm creating a table using the following logic,
    pc_create_table := 'create global temporary table revs(var1 number(5,0), ..., ...,) on commit preserve rows';
    execute immediate pc_create_table;
    When I'm attempting to insert value into this table (v_var1 is a pre-defined variable),
    pc_insert_value := 'insert into revs(var1, ..., ...,) values (v_var1, ...)'
    execute immediate pc_insert_value;
    I got the following error: "ORA-00984: column not allowed here"
    Any advise on this issue? Thanks a lot

    isaacniu wrote:
    However I got two errors in that line,
    Error(68,6): PL/SQL: SQL Statement ignored
    Error(68,18): PL/SQL: ORA-00942: table or view does not existAnd why do you want your PL/SQL code to run DDLs??
    Its not designed that way, is not a good practice and is strictly not recommended. You can read <a href ="https://forums.oracle.com/forums/profile.jspa?userID=287238">Billy Verreynne's</a> take on this :
    {message:id=10040770}
    To my suprise it's saying the table or view does not exist. According to my logic, the table "revs" created by executing pc_create_table, however it's NOT explicitly declared in other parts of this script, is this where the problem is?The Problem is, SQLs fired using Execute Immediate are evaluated, compiled, parsed and executed at run time. So when you compile procedure pc_create_table, table revs is still not created. Hence you get error when you try inserting rows in it.
    Any advises are appreciated.Get the table created by your DBA, and use insert statement without execute immediate in your procedure.

  • Very long materialized view refresh when using self-referencing table

    hi,
    I have the following query, that takes 15 sec. to execute. When building a materialized view for it, the refreshing process doesn't stop for hours. The result of the query are about 500 rows and the tables contain not more than some 1000 rows, so it's a really simple query.
       SELECT a.A,
              b.B,
              c.C
         FROM (SELECT *
                 FROM (SELECT a
                         FROM TableA)) a,
              (SELECT b
                 FROM TableA
                WHERE type = 3) b,
              (SELECT c
                 FROM TableA) c
        WHERE TRIM (a.x) = TRIM (b.y) AND b.z = c.w;I think it has something to do with the fact, that the same table is used 3 times in the query. When I look in the trace I see that the following statement is executed:
    INSERT   /*+ BYPASS_RECURSIVE_CHECK */
          INTO                                DM.Test_MV
       SELECT ...What is the + BYPASS_RECURSIVE_CHECK / hint doing? Can I deactivate it somehow?
    And why is there any difference between the query execution and the query execution when refreshing the mat view?
    Thanks for your help!

    5 digit version no? lots of bugs with mviews out there.
    theres a specific note (not a bug) on support 1115148.1 that references that hint though, so try dropping and recreating the view before refreshing.

Maybe you are looking for