Delete records based on the foreign keys of oracle 11 g
I have a requirement to remove the records from the tables in the order according to
the existing foreign keys.
I for example, the following tables and the pk, fk constraints:
create table one
(aa number (1),)
descr varchar2 (20));
ALTER table one
Add constraint a_pk key (aa) primary;
create table b
(aa number (1),)
descr varchar2 (20));
ALTER table b
Add constraint b_pk key (aa) primary;
create table c
(aa number (1),)
descr varchar2 (20));
ALTER table c
Add constraint c_pk key (aa) primary;
create table a2
(aa number (2),)
id_aa number (1).
descr varchar2 (20));
ALTER table a2
Add constraint a2_pk key (aa) primary;
ALTER table a2
Add constraint a2_fk foreign key (id_aa)
references a (aa);
create table b2
(aa number (2),)
id_aa number (1).
descr varchar2 (20));
ALTER table b2
Add constraint b2_pk key (aa) primary;
ALTER table b2
Add constraint b2_fk foreign key (id_aa)
references b (aa);
create table z
(aa number (3),)
id_aa number (1).
id_bb number (1).
descr varchar (20));
ALTER table z
Add constraint z_pk key (aa) primary;
ALTER table z
Add constraint z_fk1 foreign key (id_aa)
references a (aa);
ALTER table z
Add constraint z_fk2 foreign key (id_bb)
references b (aa);
So, I want to choose the names of the tables in such an order so as
deleting records will succeed...
I built the following sql query (using the recursive subquery factoring):
[p]
with q (r_constraint_name, table_name, constraint_name, lvl) as
(select table_name, constraint_name, r_constraint_name 1 lvl
from user_constraints one
where a.constraint_type = 'P '.
Union of all the
Select b.table_name b.constraint_name, b.r_constraint_name, q.lvl + 1 lvl
from user_constraints b
Join q
on (q.constraint_name = b.r_constraint_name)
where b.constraint_type = 'R '.
)
Select f.table_name, f.constraint_name, f.r_constraint_name, f.lvl
q f
[/ p]
I want the results as the following list:
Table-name
----------------
B2
A2
Z
A
B
C
The table - B2, A2, Z - (in any order) must first referred in the list
because they are based on the other three tables - A, B, C. Thus, in order to remove the
A, B, C table records the B2, A2, table Z records must be beleted first.
The query I posted above has the problem that it displays tables A2, B2 twice
(1 because they have a pk and 2 because they have fk referring A, B relatively tables).
Is there a solution for this problem?
Note: I use db11g v2
I wrote not all relationships of tables user_constraints (only argument constraint_name = r_constraint_name)
Thank you
SIM
I have a requirement to remove the records from the tables in the order according to
the existing foreign keys.
. . .
The table - B2, A2, Z - (in any order) must first referred in the list
because they are based on the other three tables - A, B, C. Thus, in order to remove the
A, B, C table records the B2, A2, table Z records must be beleted first.
Is there a solution for this problem?
Yes - the 'solution' is to use ON DELETE CASCADE, as appropriate or write a procedure that removes tables in the proper order.
The solution is NOT to try to use dynamic sql statements to do so.
You already know the good parent/child relationships. Simply create a procedure that uses the correct order.
Analyses are necessary in any case to determine the proper order AND press the appropriate values to use to remove the appropriate lines
Your DDL for tables and constraints must be in a version control system
Update the procedure when / if new constraints or tables are added to the application
IMHO, you must use dynamic SQL NOT to try to adjust automatically if a new constraint appears. New constraints should not appear by accident - they appear ONLY as part of a well planned release.
Tags: Database
Similar Questions
-
Deleting record based on the ID of the main table
Hello
I am trying to remove the news that are published before 2012, but the tables in detail consists the notebook of the child based on the news_id has been. Request certainly simple deletion will not workSQL> desc news Name Null? Type ----------------------------------------- -------- ---------------------------- NEWS_ID NOT NULL NUMBER(14) NEWS_DATE TIMESTAMP(0) SL_ID NUMBER(2) HEADING VARCHAR2(3120) DESCRIPTION VARCHAR2(3900) SQL> desc news_location Name Null? Type ----------------------------------------- -------- ---------------------------- NEWS_ID NUMBER(14) COUNTRY VARCHAR2(32) REGION NUMBER(2) SQL> desc news_product Name Null? Type ----------------------------------------- -------- ---------------------------- NEWS_ID NUMBER(14) PRODUCT_CATEGORY_ID NOT NULL NUMBER(14) PRODUCT VARCHAR2(27) SQL> desc news_service Name Null? Type ----------------------------------------- -------- ---------------------------- NEWS_ID NUMBER(14) SERVICE_ID NOT NULL NUMBER(14) SRVIS VARCHAR2(16) SQL> desc news_info Name Null? Type ----------------------------------------- -------- ---------------------------- NEWS_ID NUMBER(14) SOURCE VARCHAR2(203) ORIGIONAL_NEWS VARCHAR2(3900) HEADING VARCHAR2(3110) SQL> select count(*) from news where TO_CHAR(news_date,'YYYY') < 2012; COUNT(*) ---------- 8759
Please advise and thank you in advanceOnce again, I tell you, do not need ON DELETE CASCADE in the Delete query.
Just use the Delete query like: -.
delete from news where TO_CHAR(news_date,'YYYY') < 2008;
And the child tables are deleted as a result.
-
Difference between the foreign key index and secondary index
Hello
Suppose we have two primary databases,
Employee (id, company_id)
Company (id, name)
(where: the employee of the company is one to many, and I use the collections API)
If we want to perform a join between the employee and the company based on the ID of the company. I want to know the difference between the following two options:
1 - construction of a secondary index on the Employee (company_id). call this index index1. Then, we use the following code:
For each company c
index1.get (c.ID)
2 - construction of a foreign key on Employee (company_id) index where the database of foreign key was undertaken. call this index index2. Then, we use the following code:
For each company c
index2.get (c.ID)
I have two questions:
1 - What is the difference between these two options in terms of performance?
2. I know that one of the benefits of the foreign key are the application of integrity constraints (CASCADE, CANCEL, etc. to DELETE). That declare a foreign key to give me any advantage when I want to do a join? (for example a quick method, or a single statement to a join)
Thank you
Wait.It doesn't matter what the example, the only advantage of a foreign key index (above, the benefits of a secondary index) is that it imposes of foreign key constraints. There is no other advantage to a foreign key index.
-mark
-
Forgive my question. I am very new to Oracle.
How can I make sure that changes in the key primary supplier_id (concerning the supplier table) would also appear directly in the FOREIGN KEY (supplier_id) in the products table?
Is that not all the primary key and FOREIGN KEY on?
My paintings:
I created 2 tables and connect to apply in the data base referential integrity, as I learned.
CREATE TABLE - parent provider
(the numeric (10) of supplier_id not null,)
supplier_name varchar2 (50) not null,
Contact_Name varchar2 (50).
CONSTRAINT supplier_pk PRIMARY KEY (supplier_id)
);
CREATE TABLE - child products
(the numeric (10) of product_id not null,)
supplier_id numeric (10) not null,
CONSTRAINT fk_supplier
FOREIGN KEY (supplier_id)
REFERENCES beg (supplier_id)
);
I inserted the following text:
INSERT INTO provider
(supplier_id, supplier_name, contact_name)
VALUES
(5000, 'Apple', 'first name');
I expect that the supplier_id (5000) to the provider of the table also appears in the products table under key supplier_id having the same value which is 5000. But this does not happen.
How to get there?
Thanks in advance!
Hello
What is a foreign key in Oracle?
A foreign key is a way to ensure referential integrity in your Oracle database. A foreign key means that the values of a table must appear also in another table.
Ok!??
What is now the right way to implement referential integrity in your Oracle database that the values of a table must also be included in another table?
A foreign key referential integrity indeed enfore in ensuring that the value in the child table must have a corresponding parent key (otherwise you will encounter an error, as evidenced by "SomeoneElse"). However, it will never automatically insert a row in the other table.
If you are looking for a solution that automatically inserts a record in the other table, maybe you should go for triggers:
See:
-
Add the foreign key refers to a different schema
Hello
We have a database with schemaA and schemaB and we use a data model for schemaA with SQL Data Modeler.
Our data model is based on SchemaA and we do not want add schemaB or create subview in our current model for schemaB since our dev team do not want schemaB in the model
We have created a synonym in tableB schemaB shcemaA after granting select them, references to schemaA
We have added a foreign key on tableA in referencing TableB on schemaB schemaA.
for example. Add ALTER table tableA foreign constraint key(column-name) references tableB(colum-name)
So far so good.
But if we try to produce the DDL for tableA it has not provided the ALTAR of the foreign key that is based on shcmeaB
We know that we cannot add foreign key on dblinks.
How can I get the Modeler DDL from SQL data for tableA, including the foreign key
We appreciate the answers
Kind regards
Zafar
Hi zak,.
We have created a synonym in tableB schemaB shcemaA after granting select them, references to schemaA
We have added a foreign key on tableA in referencing TableB on schemaB schemaA.
You can do it in the database because TableB exists in the database and DB knows its definition, including the existing constraint of PK/UK.
This is the same model of data Modeler - you must have the definition of the table referenced in order to create the FK that refer to the constraint of PK/UK.
As it works now (we can change it) you can have modeled for SchemaA and ModelB for SchemaB. Then, you can drag & drop tableB form the Navigator to the diagram of the ModelA and TableB there will exist as an object remote read-only, you can use to create the FK.
With the help of subviews, DDL generation and configurations of reports, you can display the dev team than objects that they want to see - on the charts in generated DDL and reports.
Philippe
-
Optimize the foreign key for the removal of the cascade constraint.
Hello
JDeveloper version: 11.1.2.3.0
I saw this blog and found something new to me: http://snag.gy/qI6dY.jpg
Jdeveloper user interface, there is an option to select all tables to select the foreign key and set it for the removal of the waterfall.
My project is deployed on multiple databases. I wonder where this change is registered. None of the project files is modified.
Can I make this change (from limitations to the waterfall) for each database that I use?
Here is the blog where I saw that: http://tompeez.wordpress.com/2013/04/22/master-detail-insertdelete-sample/
I have my object associations optimized for the removal of the waterfall, but without the option above together, I always get constraint violations...
Concerning
Not sure however if you set the option the DOF looks like
"EMP_JOB_FK' FOREIGN KEY ('JOB_ID') CONSTRAINT REFERENCES 'HR '. "" SELECT JOBS "("JOB_ID') WE DELETE CASCADE If you set the option to cascade for fk Job_id from the employees table.
Timo
-
Drop partition without disabling the foreign key
Hi all
I have a table parent and child.
Parent table
create the table parent_1
(identification number,
create_date date,
Constraint parent_1_pk001 PRIMARY KEY (id))
PARTITION OF RANGE (create_date)
INTERVAL (NUMTODSINTERVAL(1,'DAY'))
(PARTITION parent_1_part VALUES LESS THAN (January 1, 2010 '));
Child table
create the table child_1
(identification number,
create_date date,
Constraint child_1_fk001 FOREIGN KEY (id)
REFERENCES parent_1 (id))
PARTITION OF RANGE (create_date)
INTERVAL (NUMTODSINTERVAL(1,'DAY'))
(PARTITION create_date_part VALUES LESS THAN (January 1, 2010 '));
I have problems to delete partition.
Parent_1
1 JULY 26, 12
2 JULY 26, 12
Child_1
1 JULY 26, 12
ALTER drop partition table CHILD_1 SYS_P274;
table altered CHILD_1.
ON THE PARENT PARTITION A FALL
ALTER drop partition table parent_1 SYS_P273;
Error report:
SQL error: ORA-02266: unique/primary keys in table referenced by foreign keys enabled
02266 00000 - "unique/primary keys in table referenced by foreign keys enabled.
* Cause: An attempt was made to truncate a single table or
primary keys referenced by foreign keys in another table.
Other unauthorized trades are a drop/truncate partition a
partitioned table or an ALTER TABLE EXCHANGE PARTITION.
* Action: Before performing the operations described above, the table, disable the
constraints foreign key in other tables. You can see what
constraints are making reference to a table by issuing the following
command:
SELECT * FROM USER_CONSTRAINTS WHERE TABLE_NAME = 'tabnam ';
PLEASE KNOW IF THERE IS A WAY TO THE PARENT PARTITION DROP WITHOUT TOGGLE FOREIGN CONSTRAINTS
Thank youSQL Error: ORA-02266: unique/primary keys in table referenced by enabled foreign keys 02266. 00000 - "unique/primary keys in table referenced by enabled foreign keys" *Cause: An attempt was made to truncate a table with unique or primary keys referenced by foreign keys enabled in another table. Other operations not allowed are dropping/truncating a partition of a partitioned table or an ALTER TABLE EXCHANGE PARTITION. *Action: Before performing the above operations the table, disable the foreign key constraints in other tables.
You can do until you disable the foreign key constraint
http://jonathanlewis.WordPress.com/2006/12/10/drop-parent-partition/
Hope this helps
Mohamed Houri
www.hourim.WordPress.com -
Identify the foreign key table
I have a table that has a few constraints that are foreign keys to other tables (see column FK_ETHNIC below). My naming conventions are consistent so they all start with 'FK_ ". In SQL, how can I find the table that the foreign key column references? I have a process that must find this table and then get all of its columns.
Thank you!
CREATE TABLE STU_BASE
(PK_ID VARCHAR2 (32), sys_guid() by default)
CONSTRAINT pk_stu_base
KEY ELEMENTARY SCHOOL
With the HELP of INDEX TABLESPACE sis_express_index
STORAGE (INITIAL 524288
NEXT 524288
PCTINCREASE 0),.
STUDENT_ID VARCHAR2 (15).
Fk_stu_base_ethnic FK_ETHNIC VARCHAR2 (32) CONSTRAINT
REFERENCES
Ethnic (PK_ID)
REMOVE THE NULL VALUE;
CREATE TABLE ETHNIC
(PK_ID VARCHAR2 (32), sys_guid() by default)
CONSTRAINT pk_ethnic
KEY ELEMENTARY SCHOOL
With the HELP of INDEX TABLESPACE sis_express_index
STORAGE (4096 INITIAL
NEXT 4096
PCTINCREASE 0),.
VARCHAR2 (2) ETHNIC,.
ETHNIC_DESC VARCHAR2 (30),
STATE_CODE VARCHAR2 (2),
FEDERAL_CODE VARCHAR2 (2))You could do a self-join with CONSTRAINTS (USER, ALL, s/n) views. You can search a constrainttype of 'R' and you can attach it to itself based on the R_OWNER and R_CONSTRAINT_NAME columns.
For example:
SELECT r1.owner AS child_owner , r1.table_name AS child_table , r2.owner AS parent_owner , r2.table_name AS parent_table FROM all_constraints r1 JOIN all_constraints r2 ON r2.owner = r1.r_owner AND r2.constraint_name = r1.r_constraint_name WHERE r1.constraint_type = 'R' ;
Published by: Centinul on February 16, 2012 15:36
-
How can I get the data in the foreign key? PHP/mysql
I managed to create registration, log-in and results pages appear for accounts of client with PHP/Mysql/Dreamweaver 8. I have another page for more information to be contained in a child table, I used the Insert Wizard to create. I can't make it work. I get either a foreign key cannot be null error or a foreign key constraint.
If I include the foreign key in the form on the page, I can manually enter the appropriate identification number, and it works. How to automatically enter the id into the foreign key column?
I got the authentication of users using e-mail, password and user type.
Thanks for your help
When someone connects, Dreamweaver creates a session variable called $_SESSION ['MM_Username"]. Use this session variable to create a recordset object to get the ID of the user, who can then be entered in the child table's foreign key field.
Dreamweaver automatically updates the code for recordsets immediately above the DOCTYPE declaration, then you will need to move above the code for the server behavior insert record. So it must be in the following order:
- Recordset to get the user ID
- Insert the record to the child table
-
How to find the foreign key in pl/sql
Error from the 1 in the command line:
DELETE FROM ZKET_SOLE WHERE IID_SOLA = 1
Error report:
SQL error: ORA-02292: integrity constraint (IRCKIS. ZKETSTIP_ZKET_FK) violated - book of the foundling
02292 00000 - 'constraint integrity (s.%s) violated - child notebook found. '
* Cause: attempted to remove a parent key value that was a stranger
dependence.
* Action: remove dependencies first then the parent or disable the constraint.
I need to find the foreign key, but I don't know how. I know it must be in the dictionary, but I'm not. I don't have access to the ER model.
THXRun this query:
select * from dba_constraints where owner = 'IRCKIS' and constraint_name = 'ZKETSTIP_ZKET_FK'
-
SQL statement error INSERT The conflicted with the FOREIGN KEY constraint
I recently installed a reporting for vmware vsphere software, but I get a SQL error. I opened a request for assistance with vmware, but so far they have not come up with a solution. The error is caused by: com.microsoft.sqlserver.jdbc.SQLServerException: instruction INSERT The conflicted with the FOREIGN KEY constraint 'FK_CB_VSM_NETWORK_VC_ID '. The conflict occurred in database 'VCChargebackVCC02', table "dbo." " CB_VSM_SERVER', column 'VC_ID '. I don't know a lot about SQL, so I'm lost in the extent of troubleshooting is concerned. If anyone has any ideas I'd love to hear them.
SQL questions are better posed on Technet. They are better equipped to manage the
http://social.technet.Microsoft.com/forums/en-us/categories/
-
Term plurals changes the name of the foreign key in the relational model
Hello
I use a glossary with plurals for entities such as Budget turned to the budgets of the table in the relational model. Unfortunately (for me) it also changes the name of the foreign key. In the related entity, an attribute (for example) is Budget_fiscal year, I expect in the relational model, being the same, but it is transformed into budgets_fiscal_year (budgets in the plural rather than keep him in singular form).
How can I avoid any change in the attribute names (in the process of engineering in the relational model) but always turn the names of entities from the singular to the plural names for tables?
Thank you and best regards
Robert
Hi Philippe
Your suggestion 1) works - thank you! budgets_fiscal_year is the attribute of pk exercise in my budget of the entity. It seems a standard behavior of the Data Modeler to compose the UID of the relationship of budgets_fiscal_year (for some reason, this column is not taken the logical model, but the relational model). I would prefer that it be appointed budget_fiscal_year.
I have not defined any parameter for this (intentionally). But maybe somewhere there by default. Could you tell me where the design parameters in Data Modeler to learn how to configure the definitions mentioned in 2)?
As I'm always busy with the model of reverse engineering data, I'll wait for DM 4.1.1.888.
Best regards
Robert
-
Schema import Gets the foreign key number
Hi all;
Scott has a table named rank-> he has primary key-> different tablespace
Sharma has a table named emp-> he has foreign key-> different tablespace
$ imp/System Manager queue = refresh_sharma.dmp log = refresh_sharma_imp.log fromuser = touser = sharma sharma
Import: Free 11.2.0.1.0 - Production Thursday, may 7, 18:35:03-2015
Copyright (c) 1982, 2009, Oracle and/or its affiliates. All rights reserved.
Connected to: Oracle Database 11g Enterprise Edition Release 11.2.0.1.0 - Production
With partitioning, OLAP, Data Mining and Real Application Testing options
Export file created by EXPORT: V11.02.00 direct
import in US7ASCII and AL16UTF16 NCHAR character set
import server uses WE8MSWIN1252 (possible character set conversion) character set
Customer export uses the (possible character set conversion) WE8MSWIN1252 character set
. import of objects in SHARMA SHARMA
. . import of partition "CONT_EMP": "P1" 4000 imported lines
. . import of partition "CONT_EMP": "P2" 5000 imported lines
. . import of partition 'CONT_EMP': 'P3' 5000 imported lines
. . "DEPT" table import 12 lines imported
. . import of table 'EMP' 68278 imported lines
. . importing table "EMP_AUDIT" 4 imported lines
. . table 'Method' import 68000 lines imported
. . importing table "EMP_PERS_INFO" 68278 imported lines
. . importing table "EMP_PROJ_INFO" 68278 imported lines
. . table 'LOGTAB' import 603 lines imported
. . table import "PAYROLL" 186282 imported lines
. . import of table 'of the PROJECT"22 rows imported
. . importation of "TAB1" 4000000 imported table rows
. . table import 'TRANSPORT' 0 rows imported
IMP-00017: statement failed with error ORACLE 1031:
'ALTER TABLE 'EMP' ADD 'EMP_EMPLEV_C12_FK' OF CONSTRAINT FOREIGN KEY ("EMP_LEVE" '.
""L") REFERS TO"SCOTT" CATEGORY"("GRADE_NAME") ENABLE NOVALIDATE.
IMP-00003: ORACLE error 1031
ORA-01031: insufficient privileges
About to activate the constraints...
IMP-00017: statement failed with error ORACLE 2430:
' ALTER TABLE 'EMP' ENABLE CONSTRAINT "EMP_EMPLEV_C12_FK"
Import completed successfully with warnings.
30, 31 line number is display error.
'ALTER TABLE 'EMP' ADD 'EMP_EMPLEV_C12_FK' OF CONSTRAINT FOREIGN KEY ("EMP_LEVE" '.
""L") REFERS TO"SCOTT" CATEGORY"("GRADE_NAME") ENABLE NOVALIDATE.
After the import operation, to recreate the foreign key is the right option. but
By performing the import operation, how can all I avoid this error dump file or log file?
I don't want to use constraints = N.
Thanks in advance
You gave * of * SCOTT * at * SHARMA. The grant received by SHARMA not getting exported when you export SHARMA. So, it is not imported when you import SHARMA. If you did an export and import of SCOTT before SHARMA, the award of the cross-schema would have also been imported. (Subsidies granted by a user are exported with the user, the subsidies received by a user are not exported with the user).
Hemant K Collette
-
Rename the foreign key constraint
Hello
I have table tbl_a with a column a_col1 SEO tbl_b.b_col1
I want to create the name of the foreign key as FK_A_COL1 constraint which is FK_ < COLUMN NAME OF the CHILD >.
Foreign naming key standards does not have the use of the name of the child under the name column.
Is there any other solution/script to achieve this?
Thank you.fkeys = model.getFKIndexAssociationSet().toArray(); for (var i = 0; i
;//also can use fk.getTable().getAbbreviation()fkname = "FK_"+fk.getTable().getName();cols = fk.getColumns();for( var k = 0;k -
Renaming of the foreign keys in the relational model
Hello
I'm new to the Data Modeler, we use v 3.0.0.66.5 and Oracle 11 g, and I am trying to build a logic and a relational model for a new application.
We always call our primary keys as the ID, this causes me a problem with my names of foreign keys in the relational model, as they show as ID #. Is it possible to add the abbreviated of the table of the foreign key?
Thanks in advance
SueYes it is.
Take a look at the tools > preferences, select Data Modeler > naming Standard > model, you can specify the standard you want to use for your foreign key. You can apply this designation to existing models and all new created FK uses the same model. To apply the standard to existing templates, select the relational model in the browser, right-click to display the context menu and select the menu "apply Naming standards... ».
Sue
Maybe you are looking for
-
After the update of ff22, why Web site icon is missing in awesome bar?
In older versions of ff, an icon (logo) of the Web site I was visiting appeared in the impressive bar just to the left of "http." Overview of the slider he grew up balloon with description. In hover above him now brings up a ToolTip text that says th
-
Computer HP laptop will not update windows download 8 pass from 13%
Laptop HP Pavilion g6 windows 8
-
Porque no puedo ver the mid tower plasma en mi imagen? ago tiene el HDMI cable
NO PUEDO VER THE MI PANTALLA PLASMA E IMAGEN IS EL EL CABLE HDMI CONNECTED WITHOUT THE DETECTA Y TV
-
Increases time to start w/HP Officejet J4580?
I just bought and installed an HP Officejet J4580. I am running Vista Home Premium (32) with all updates installed. Time to start the computer after installation of the printer software has increased 1.5-minute when starting and restarting. Any ideas
-
Static RP RP Configuration vs PIM candidate election
Hi team, I have static RP for a group range (225.0.0.0 to 255.0.0.0) and I configured dynamic RP ("bootstrap" mechanism) for the same group range. that one will be elected as the RP - SET. Please let know us your opinion. Thank you very much in advan