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
Similar Messages
-
Best practices in Queue table maintenance
Hi Fellow AQ Users,
I am looking to hear from the community about best practices in queue table maintenance.
I have been mining through metalink about various Oracle recommendations and putting
together a set of recommendations as a starting point for my DBAs.
I am looking to answer questions like these --
How often (in relation to messaging load) would you coalesce and rebuild the indexes?
How often would you rebuild the table itself to get rid of the high water mark issues ?
and what procedure would you use to do that?
Would really love to learn from your experiences in this area. We are using 9.2.0.7
64 bit DB and have plans to go to 10g over the next year. So, I am looking at 9i related
stuff and then 10g.
Thanks
VijayHello,
In general you coalesce once per day ideally during a quiet time to avoid ORA-54 errors as per <Note:271855.1>. Some customers do it more often than that but once per day is a good starting point.
In terms of shrinking the queue tables you can use the procedure in <Note:304522.1> with a null 3rd parameter. This is an offline procedure so you could only run it during a maintenance window. In 10.2 onwards you can dynamically shrink the queue table and IOTS. Again it depends on exactly what you are doing with your queue tables how often you might need to do this.
Thanks
Peter -
Hi Gurus,
Are GT_ , GS_ , LT_ , LS_ --- the Best practices in Internal table naming convention ????
I have seen this naming convetions adhered in standard programs .
What each one of the below signify
GT_ , GS_ , LT_ , LS_ ???????
Regards
Jaman
Message was edited by:
ABAP TechieHello
I use the following naming conventions:
- G = global variable
- L = local variable
- T = internal table
- S = structure
- D = field
That's how the combinations look like:
- GT_ITAB = global itab
- GS_STRUC = global structure
- GD_FIELD = global field
- LT_ITAB = local itab
- LS_STRUC = local structure
- LD_FIELD = local field
Function module parameters have to stick to the following rules:
- I = importing
- E = exporting
- [C = changing -> never used]
- IT_ITAB = imported table type (itab)
- IS_STRUC = imported structure
- ID_FIELD = imported field
- ET_ITAB = exported table type (itab)
- ES_STRUC = exported structure
- ED_FIELD = exported field
Depending on their semantics TABLES parameters look like:
- IT_ITAB = imported data
- ET_ITAB = exported data
- XT_ITAB = changing data (import & export)
Here are the conventions for FORM routine parameters:
- UT_ITAB = using itab (data are usually treated like constants; no changes will be transfer - although possible - to the calling program)
- CT_ITAB = changing itab (if it is semantically an exporting itab then one of the very
first statements in the routine is: REFRESH ct_itab. )
- US_STRUCT
- UD_FIELD
- CS_STRUCT
- CS_FIELD
Conventions for class/interface parameters:
- IT_ITAB = importing table type
- IS_STRUC = importing structure
- ID_FIELD = importing field
- ET_ITAB = exporting table type
- ES_STRUC = exporting structure
- ED_FIELD = exporting field
- RT_ITAB = returning table type
- RS_STRUC = returning structure
- RD_FIELD = returning field
Conventions for class/interface attributes:
- MT_ITAB = table type
- MS_STRUC = structure
- MD_FIELD = field
- MC_CONST = constant
<b>Question</b>: Are there any advantages of such elaborated naming conventions?
My answer to this question is: Yes, definitively.
I believe that the advantage of semantically differentiating TABLES parameters of function modules is quite obvious:
CALL FUNCTION 'Z_BAD_NAMING'
TABLES
itab1 = ...
itab2 = ...
itab3 = ... .
CALL FUNCTION 'Z_GOOD_NAMING'
TABLES
it_itab1 = ...
et_itab2 = ...
xt_itab3 = ... .
I also believe that my naming conventions clearly enhance <b>readability </b>and <b>maintainability </b>of my programs.
Regards
Uwe -
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 helpsyou 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!
JonYou 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. -
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; -
Best Practice For Referencing JPEG Path Using Servlets To Prepare HTML IMG
I am migrating a legacy app from Tomcat 5 to Weblogic 11g (10.3). In the legacy app, servlets write HTML that uses relative paths for <IMG src="../images/img.jpeg"> and <script src="../javascript/js.js">. The app is deployed as an exploded archive. Unfortunately, none of the images or script are being loaded. I've tried using http://serverIP:portNum/contextName/images/img.jpeg"> but it doesn't work. I've also checked to get the name of the context in the servlet and it's the root context. Could it have something to do with me having to append .war onto the application when I deploy it? Would it help if I deployed it as a war inside an ear? Basically, I want some best practices for doing this on Weblogic 11g. There are a lot of images and javascript and I'm really hoping they don't have to be inserted using ClassLoader.getResourceAsStream()... thank you.
Best Practice:
1. Move Static files like images, css, java scripts to a web server infrastructure if available.
2. If this is not your case, then please send your directory information how you have packaged your EAR. I can advice :) -
Best Practice to Copy Table to Different Schema?
This is what I tried:
1. Create USER2 new user that uses TBS2 as default Tablespace
2. Perform exp (resides on TBS1 Tablespace)
3. Perform imp using fromuser and touser parameter to USER2
What I noticed is that the table that was imported to USER2 still resides on the same tablespace which suppose to be on TBS2.
Can someone help me perform this steps?mrp wrote:
will this option recreate index?The best way to find answers of such questions would be to test it yourself.
SQL> conn aman/aman
Connected.
SQL> create table test as select * from scott.dept;
Table created.
SQL> create index tidx on test(deptno);
Index created.
SQL> select object_name, object_type from user_objects;
OBJECT_NAME
--------------------------------------------------------------------------------OBJECT_TYPE
TIDX
INDEX
TEST
TABLE
SQL> create table test2 as select * from test;
Table created.
SQL> column object_name format a40
SQL> select object_name, object_type from user_objects;
OBJECT_NAME OBJECT_TYPE
TIDX INDEX
TEST TABLE
TEST2 TABLE
SQL>So did the index get created for the 2nd table or not?
Aman.... -
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,
MarkFirst 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. -
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,
JI 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
Maybe you are looking for
-
How to Determine the first day of the current Fiscal Year
I am a SQL Server developer who is trying to to learn Oracle SQL. I am trying to write a query that will 1) determine the month number and if the number is 10, 11, or 12, will return '01-Oct-' of the current Calendar year. If the month number is betw
-
How to define Is message worked up by receiver?
I see OK in message monitoring. But JDBC receiver does't insert data. AdapterMonitoring showws only last status - it doesn't help. How to define Is message worked up correctly by receiver? There is EAI pattern - Invalid Message Chanel. How to implem
-
New Announcement in this forum
I just saw, that Jan created a new announcement on top of this forum. Good ! => If you have java code to display on the forum, surround it with tags and the output formatter will format the code for you with syntax highlighting and with indentation i
-
How to make it Bigger??
I have a large display and enjoy the larger image, its ease of viewing. I would like to increase the size of Safari's fonts, not the 'command +' but the actual fonts on the page headers, tab headers etc.. Reading in Safari is tiring because of this.
-
Mavericks doesn't recognize unknown file extensions as extensions
I did a clean install of Mac OS X 10.9 mavericks recently, and now the darnest things is happening: I can't seem to get Mac OS X to recognize that unknown file extensions are file extensions. I don't mean I'm having trouble associating file extension