DELETE tbemp.emp_id,
tbadd.emp_id
FROM TBEMPLOYEE tbemp
JOIN TBADDRESS tbadd ON (tbemp.emp_id=tbadd.emp_id)
Oracle 11g not compile it
This delete statement is not valid in Oracle. There are other statements for deletion, one could be
DELETE FROM TBEMPLOYEE tbemp
WHERE EXISTS (select 'x'
from TBADDRESS
where tbemp.emp_id=tbadd.emp_id);
You can't delete directly from multiple tables with a join.
But you can enforce a foreign key constraint with ON DELETE CASCADE.
ALTER TABLE tbaddress ADD CONSTRAINT fk_emp FOREIGN KEY (emp_id) REFERENCES tbemployee (emp_id) ON DELETE CASCADE;
DELETE FROM tbemployee; -- This also deletes referencing keys from tbaddress
Related
Parent table A with some records.
Child table B with 0 records.
I have a cursor to do truncation on these tables in reverse tree order (i.e. truncate child first, then parent)
But I'm still getting this error when I truncate the parent table 'ORA-02266: unique/primary keys in table referenced by enabled foreign keys' error, despite the fact that the child table has no records at all.
However, when I do 'Delete from ' in the same order, all constraint related errors were avoided. And 'Delete from' takes really long time to run.
I don't want to disable or drop any constraints.
However, when I do 'Delete from ' in the same order, all constraint related errors were avoided.
That's the only way if you have constraints enabled. You cannot truncate. If you still want to truncate the table, then you could find the constraint name from user_constraints, and then DISABLE them:
ALTER TABLE table_name DISABLE CONSTRAINT constraint_name;
Then you could TRUNCATE the table, and re-enable the constraint:
ALTER TABLE table_name ENABLE CONSTRAINT constraint_name;
If your table has ON DELETE CASCADE option, then from Oracle 12.1 onward, you could use:
TRUNCATE TABLE table_name CASCADE;
Note, both the DELETE CASCADE and the TRUNCATE CASCADE will fail if any of the relationships in the hierarchy are not defined with the ON DELETE CASCADE clause.
There are three ways to delete from parent/child tables:
CREATE TABLE par (i NUMBER CONSTRAINT par_pk PRIMARY KEY);
CREATE TABLE chi (i NUMBER CONSTRAINT chi_fk REFERENCES par(i) ON DELETE CASCADE);
INSERT INTO par VALUES(1);
INSERT INTO chi VALUES(1);
1) If you have Oracle 12 or later, and you have foreign keys with ON DELETE CASCADE, you can use TRUNCATE CASCADE, which I expect to be the fastest option:
TRUNCATE TABLE par CASCADE;
Table PAR truncated.
SELECT count(*) FROM par;
0
SELECT count(*) FROM chi;
0
2) If your foreign keys are defined with ON DELETE CASCADE, you can use DELETE, which I expect to be the slowest option:
DELETE FROM par;
1 row deleted.
SELECT count(*) FROM par;
0
SELECT count(*) FROM chi;
0
3) Otherwise, you can disable the foreign keys, truncate the tables and reenable the foreign keys. This is fast, but is a little bit more risky than the other options (please check that the constraints are all valid afterwards):
ALTER TABLE chi DISABLE CONSTRAINT chi_fk;
TRUNCATE TABLE chi;
TRUNCATE TABLE par;
ALTER TABLE chi ENABLE CONSTRAINT chi_fk;
AFAIK, it is not possible to alter a foreign key from normal to ON DELETE CASCADE. I guess you have to drop and recreate them:
ALTER TABLE chi DROP CONSTRAINT chi_fk;
ALTER TABLE chi ADD CONSTRAINT chi_fk REFERENCES par(i) ON DELETE CASCADE;
how can this statement:
DELETE FROM passage
WHERE passageid NOT IN
(
SELECT passageid from PreEndedPassages_passages
UNION SELECT fromPassageid from severalvisit
UNION SELECT toPassageid from severalvisit
UNION SELECT registerPassageid from stationobjects WHERE registerpassageid IS NOT NULL
UNION SELECT beginPassageid from stationobjects WHERE beginPassageid IS NOT NULL
UNION SELECT endPassageid from stationobjects WHERE endPassageid IS NOT NULL
)
throw this exception?
The DELETE statement conflicted with the FOREIGN KEY constraint "FK_statobj_begpasid". The conflict occurred in database "db.mdf", table "dbo.stationobjects", column 'beginpassageid'.
I have no clue, but it happened. beginPassageId is a foreign key on passageid.
EDIT:
Consider the NOT IN. I want to delete all passages that don't exist in one of its related tables. It usually works, but it happened once.
Thank you.
It means passage is parent table. and stationobjects is child table. You are trying to remove passageid from passage table which is present in stationobjects table as well.
First try to remove those passageid from stationobjects and then you can run this delete statement.
Alternate approach is cascade delete, if your DB supports that.
this kind of occur when you have a foreign key relationship in the two table.
This violates the Refrential Integrity .
so if you delete record from the primary table and record exist in foreign key table,
then you have two options:
1. either set the delete rule to cascade so that when ever you delete primary record the foreign key table record will get automatically deleted.
2.delete record from foreign key table first then from primary key table.
These kind of errors come up when table A foreign key is table B primary key and when you try to delete record in table A that has linking in table B, then deletion will not happen. Try dropping foreign key relation before delete. Same way truncate is used in tables by dropping fk relations and rebuilding them again after the table is reset
I have a problem with sql server, when I want to have 3 table and make relationship between them, and change the "On Update" property to "cascade".
this problem happend when I want to save the diagram:
Introducing FOREIGN KEY constraint 'FK_Company_Slave' on table 'Company' may cause cycles or multiple cascade paths. Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints.
Could not create constraint. See previous errors.
in this picture, I define my data base, FK and ....
thanks.
First:
A FOREIGN KEY in one table points to a PRIMARY KEY in another table. if you don't want to use PRIMARY KEY on other table in order to foreign key, you must be create unique index on the table.
Second:
you can create after trigger on Master table in order to develop on update cascade manually. In other word your foreign key between Company table and Master table created without on update cascade and then create following trigger on master to update company table after changed row in Master table.
create trigger triggername on dbo.[Master]
After Insert
AS Begin
Update Company
Set MasterKey = I.MasterKey
From Inserted I
Inner join Deleted D on D.Code = I.Code
Where Company.MasterKey = D.MasterKey
End
I have one question about DELETE query in SQL. I have 3 child tables say B,C,D and one parent Table A. Priamry key of A is shared in all its child tables. If I have to delete a record from the child tables and then from the parent in a single SQL then is it possible? If yes can you guide me for an SQL query contruct? If not is it at least possible to delete record from the child tables in a single query?
If you don't have a foreign keys with ON DELETE CASCADE then you should do it with transaction:
BEGIN;
DELETE FROM B WHERE ...
DELETE FROM C WHERE ...
DELETE FROM D WHERE ...
COMMIT;
ADDED:
If you use mysql read DELETE doc and discussion here stackoverflow delete-from-two-tables-in-one-query
Nahue's comment and sufleR's answer are right. If you have an ON DELETE CASCADE specified on the foreign key relationships, you will be able to delete from all these tables using a single DELETE statement.
If you do not have this constraint enforced, you can enforce it with ALTER TABLE statement. I would take your schema as
A (a_pk, ...) -- PRIMARY KEY specified on a_pk
B (b_pk, a_fk, ...)
C (c_pk, a_fk, ...)
D (d_pk, a_fk, ...)
Then,
ALTER TABLE b
ADD CONSTRAINT b_a_fk
a_fk REFERENCES a(a_pk) ON DELETE CASCADE;
ALTER TABLE c
ADD CONSTRAINT c_a_fk
a_fk REFERENCES a(a_pk) ON DELETE CASCADE;
ALTER TABLE d
ADD CONSTRAINT d_a_fk
a_fk REFERENCES a(a_pk) ON DELETE CASCADE;
All the tables will enforce a FOREIGN KEY with ON DELETE CASCADE referential constraint on all these tables.
Now, if you issue
DELETE FROM a WHERE a_pk = <some value>
then this would delete records from B, C and D where each of their a_fk = <some value>.
Note that I have used Oracle syntax in my queries. You will have to convert these to suit your DBMS syntax but I don't think that is necessary as this is the standard syntax.
Create Trigger:
SELECT #oldVersionId = (SELECT DISTINCT VERSION_ID FROM Deleted)
SELECT #newVersionId = (SELECT DISTINCT VERSION_ID FROM Inserted)
SELECT #appId = (SELECT DISTINCT APP_ID FROM Deleted)
UPDATE [TableName]
SET [VERSION_ID] = #newVersionId
WHERE (([VERSION_ID] = #oldVersionId) AND ([APP_ID] = #appId) )
Can this Trigger be replace with a Foreign Key to update the VERSION_ID ?
What I think could be a problem is the AND condition, how to express that in a FK with On del/update Cascade?
FOREIGN KEY CONSTRAINTS don't update anything. They check the values being written to a record and cause the write to fail if they cause a constraint to fail.
Also, as #marc_s points out in his comment, triggers in MS SQL Server are set based. The INSERTED and DELETED tables can hold multiple records at once. Your code only works for one record.
You could try something along these lines...
UPDATE
table
SET
VERSION_ID = inserted.VERSION_ID
FROM
table
INNER JOIN
deleted
ON table.VERSION_ID = deleted.VERSION_ID
AND table.APP_ID = deleted.APP_ID
INNER JOIN
inserted
ON deleted.PRIMARY_KEY = inserted.PRIMARY_KEY
EDIT
I just read your comment, and I think I understand. You want a foreign key constraint with ON UPDATE CASCADE.
You use this format to create that with DDL.
ALTER TABLE DBO.<child table>
ADD CONSTRAINT <foreign key name> FOREIGN KEY <child column>
REFERENCES DBO.<parent table>(<parent column>)
{ON [DELETE|UPDATE] CASCADE}
Or you could just SQL Server Management Studio to set it up. Just make sure the ON UPDATE CASCADE is present.
I cannot really tell you what you're looking for - you're too unclear in your question.
But basically, if two tables are linked via a foreign key constraint, of course you can add a clause to that to make sure the child table gets updated when the parents table's PK changes:
ALTER TABLE dbo.ChildTable
ADD CONSTRAINT FK_ChildTable_ParentTable
FOREIGN KEY(ChildTableColumn) REFERENCES dbo.ParentTable(PKColumn)
ON UPDATE CASCADE
The ON UPDATE CASCADE does exactly that - if the referenced column (the PKColumn in ParentTable) changes, then the FK constraint will "cascade" that update down into the child table and update it's ChildTableColumn to match the new PKColumn
Read all about cascading referential integrity constraints and what options you have on MSDN Books Online