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

Similar Messages

  • 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

  • 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.

  • 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().

  • 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 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!!

  • 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

  • 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

  • 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;

  • Need help on self referencing a ssrs report

    Hi All,
    I have a graph on one of my report which shows data on level 1 by default and go on showing level 2 and level 3 data on successive clicks. This has been achieved by self referencing a ssrs report and passing respective parameters. Now to identify which level
    data needs to be shown on graph, I have used one more parameter which default value is 1 and go on increasing to 2 then 3 on successive click and this parameter value is used in group expression of graph. This works just fine.
    But the real problem has occurred when you go and select report parameters which are corresponding to level 1, level 2 and level 2 values and click on apply in between. For e.g. Assume level 1=Region, level 2=SubRegion and level 3=Country. When you run this
    report it shows region wise data on graph and value of fourth parameter is 1, now when you click on graph it takes you to level 2 i.e. it shows sub region wise data on graph and value of fourth parameter is 2 but when you go and select all region, sub region
    and countries from report parameters and click on apply button then it should show data on graph region wise but since the time you were selecting parameter data was sub region wise and value of fourth parameter was 2 it shows data for all sub regions which
    is weird and not acceptable at all. 
    I am hoping SSRS should provide a way to pass parameters just like we pass in action on any control within ssrs report to solve this issue. Please help me out to solve this issue or let me know if need more infor.

    Hi,
    There was an error reading from the pipe: Unrecognized error 109 (0x6d).
    One reason was inconsistent binding between client and server <netNamedPipeBinding> <security mode="None"></security>... (no
    communication)
    The other intermittent issue was time-out related.
    For more information, you could refer to:
    http://stackoverflow.com/questions/15836199/wcf-namedpipe-communicationexception-the-pipe-has-been-ended-109-0x6d
    http://stackoverflow.com/questions/22334514/wcf-named-pipe-error-the-pipe-has-been-ended-109-0x6d
    Regards

  • SAP Query: How to filter records from SAP Query output before display

    Hi Friends,
      Can I delete records from an SAP query basic list before it is displayed?
    For example I want to delte all the orders whose system status is "RELEASED" before the basic list of that SAP query is displayed.
    I have gone through SAP help and found out that we can write some code in <b>END code</b> section which will execute before the basic list of the query is displayed. But I could not figure out how the code this...following is an excerpt form SAP help.
    <b>"The END-OF-SELECTION code consists of two parts (Before list output and After list output). The first part is processed before the list is output and the second part afterwards."</b>
    Can anybody help me?
    Regards,
    Bharat.
    Message was edited by:
            Bharat Reddy V

    Try this simple procedure. <b>Hope</b> this should work for you.
    You do the slection of the status in the List-Processing. say your final field of status flag is GF_STATUS.
    Immediatly after that use this within the List-Processing.
    CHECK GF_STATUS EQ '<RELEASED STATUS>'
    How it works:
    SELECT  <>       "<-------Query processing(system code).
    *< Your code put in the List processing
    CHECK GF_STATUS EQ '<RELEASED STATUS>'   "< --only released records passed.
    *>
    ENDSELECT      "<-----Query endselect(system code).
    Please let me know the result.
    Regards,
    A.Singh
    Message was edited by:
            Amarjit Singh

  • Deleting records from Self-Referencing Table

    I am using this query to dodge the foreign key error when trying to delete a record from a table that has primary key and referencing foreign key in the same table. It works with smaller set of data but for a table with 400,000 records it fails with error
    : maximum recursion limit of 500 reached. I changed maxrecursion to 3267 and even 0. but no records were returned it infact went to infinite loop..
    Please help if u have an alternative solution othr than a cascade trigger(which I am already considering)
    WITH    q AS
            SELECT  id, siteUrl
            FROM    TestComposite
            WHERE   id = 42
                    AND siteUrl = 'site1'
            UNION ALL
            SELECT  tc.id, tc.siteUrl
            FROM    q
            JOIN    TestComposite tc
            ON      tc.parentID = q.id
                    AND tc.siteUrl = q.siteUrl
    select * 
    FROM    TestComposite
    WHERE   EXISTS
            SELECT  id, siteUrl
            INTERSECT
            SELECT  id, siteUrl
            FROM    q
    Thanks,
    J

    I am using this query to dodge the foreign key error when trying to delete a record from a table that has primary key and referencing foreign key in the same table. It works with smaller set of data but for a table with 400,000 records it fails with error
    : maximum recursion limit of 500 reached. I changed maxrecursion to 3267 and even 0. but no records were returned it in fact went to infinite loop..
    That is a questionable approach. Don't dodge table constraints. They have a reason to be there. Deep recursion is also doubtful approach.
    USE tempdb;
    GO
    SELECT * INTO Employee FROM AdventureWorks.HumanResources.Employee;
    GO
    ALTER TABLE Employee ADD constraint PK PRIMARY KEY (EmployeeID);
    ALTER TABLE Employee ADD constraint fkPK FOREIGN KEY (ManagerID) REFERENCES Employee(EmployeeID);
    GO
    SELECT * FROM Employee;
    GO
    -- Staff - no child records
    DELETE Employee WHERE EmployeeID = 283; -- (1 row(s) affected)
    -- Manager - child records
    DELETE Employee WHERE EmployeeID = 284;
    Msg 547, Level 16, State 0, Line 19
    The DELETE statement conflicted with the SAME TABLE REFERENCE constraint "fkPK". The conflict occurred in database "tempdb", table "dbo.Employee", column 'ManagerID'.
    The statement has been terminated.
    Kalman Toth Database & OLAP Architect
    SQL Server 2014 Design & Programming
    New Book / Kindle: Exam 70-461 Bootcamp: Querying Microsoft SQL Server 2012

  • 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.

  • 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.

  • Query output help

    Oracle 11.2.0.1
    Windows
    create table storetab
    deptname  varchar2(20),
    grpcode    varchar2(10),
    grpname    varchar2(10),
    itemname  varchar2(10),
    specs      varchar2(10),
    qty        number,
    rate      number,
    amount    number
    insert into storetab values('STORE','GRP1','GRP1','ITEM1','',0,0,0);
    insert into storetab values('STORE','GRP2','GRP2','ITEM2','',0,0,0);
    insert into storetab values('STORE','GRP3','GRP1','ITEM3','',0,0,0);
    insert into storetab values('PURCHASE','GRP7','GRP9','ITEM6','',0,0,0);
    insert into storetab values('SALES','ACM2','GRP3','ITEM4','',0,0,0);
    insert into storetab values('SALES','ACM5','GRP6','ITEM5','',0,0,0);
    insert into storetab values('SALES','QOW2','GRP3','ITEM7','',0,0,0);
    insert into storetab values('STORE','IDS9','GRP10','ITEM1','',0,0,0);
    insert into storetab values('STORE','KKZ0','GRP2','ITEM6','',0,0,0);
    insert into storetab values('ACCOUNTS','GRP3','GRP23','ITEM4','',0,0,0);
    insert into storetab values('IT','PQM7','GRP221','ITEM2','',0,0,0);
    insert into storetab values('IT','GRP1','GRP32','ITEM3','',0,0,0);
    insert into storetab values('IT','PQM3','GRP1','ITEM5','',0,0,0);
    Select * from storetab;
    DEPTNAME            GRPCODE    GRPNAME    ITEMNAME  SPECS                                          QTY      RATE    AMOUNT
    STORE                GRP1      GRP1      ITEM1                                                    0    0          0
    STORE                GRP2      GRP2      ITEM2                                                    0    0          0
    STORE                GRP3      GRP1      ITEM3                                                    0    0          0
    PURCHASE            GRP7      GRP9      ITEM6                                                    0    0          0
    SALES                ACM2      GRP3      ITEM4                                                    0    0          0
    SALES                ACM5      GRP6      ITEM5                                                    0    0          0
    SALES                QOW2      GRP3      ITEM7                                                    0    0          0
    STORE                IDS9      GRP10      ITEM1                                                    0    0          0
    STORE                KKZ0      GRP2      ITEM6                                                    0    0          0
    ACCOUNTS            GRP3      GRP23      ITEM4                                                    0    0          0
    IT                  PQM7      GRP221    ITEM2                                                    0    0          0
    DEPTNAME            GRPCODE    GRPNAME    ITEMNAME  SPECS                                          QTY      RATE    AMOUNT
    IT                  GRP1      GRP32      ITEM3                                                    0    0          0
    IT                  PQM3      GRP1      ITEM5                                                    0    0          0
    13 rows selected.
    Required output:
    GRPCODE          GRPNAME          ITEMNAME     SPECS     QTY     RATE     AMOUNT
    ACCOUNTS--->GRP3          GRP23          ITEM4
    IT--->PQM7          GRP221          ITEM2
    GRP1          GRP32          ITEM3
    PQM3          GRP1          ITEM5
    PURCHASE--->GRP7          GRP9          ITEM6
    SALES--->ACM2          GRP3          ITEM4
    ACM5          GRP6          ITEM5
    QOW2          GRP3          ITEM7
    STORE--->GRP1          GRP1          ITEM1          
    GRP2          GRP2          ITEM2     
    GRP3          GRP1          ITEM3
    IDS9          GRP10          ITEM1
    KKZ0          GRP2          ITEM6
    Thanks.

    Every where :
    Select case when DEPTNAME = lag(DEPTNAME) over (order by DEPTNAME) then null else deptname end DEPTNAME,
           GRPCODE,
           GRPNAME,
           ITEMNAME,
           specs,
           qty,
           rate,
           amount
    from storetab
    DEPTNAME
    GRPCODE
    GRPNAME
    ITEMNAME
    SPECS
    QTY
    RATE
    AMOUNT
    ACCOUNTS
    GRP3
    GRP23
    ITEM4
    0
    0
    0
    IT
    PQM3
    GRP1
    ITEM5
    0
    0
    0
    PQM7
    GRP221
    ITEM2
    0
    0
    0
    GRP1
    GRP32
    ITEM3
    0
    0
    0
    PURCHASE
    GRP7
    GRP9
    ITEM6
    0
    0
    0
    SALES
    ACM5
    GRP6
    ITEM5
    0
    0
    0
    ACM2
    GRP3
    ITEM4
    0
    0
    0
    QOW2
    GRP3
    ITEM7
    0
    0
    0
    STORE
    KKZ0
    GRP2
    ITEM6
    0
    0
    0
    GRP3
    GRP1
    ITEM3
    0
    0
    0
    GRP2
    GRP2
    ITEM2
    0
    0
    0
    GRP1
    GRP1
    ITEM1
    0
    0
    0
    IDS9
    GRP10
    ITEM1
    0
    0
    0
    Ramin Hashimzade

Maybe you are looking for