on delete cascade is deleting entire child table - sql-server

I have two tables:
Parent, which has a primary key (parentID) and some other fields of type varchar(50) and Child which is as follows:
childID, primary key
parentID, foreign key references Parent (parentID)
otherID, foreign key to another table
If I delete a row from Child, no problem.
If I delete a row from Parent, I get a foreign key constraint error on Child -- good, that's correct.
Now, I modify the relationship for the parentID key and set delete to cascade instead of No Action
(I'm using the 2008 server studio, right-clicking on column, choose Modify, then right click on the table design and choose Relationships. I then choose the relationship for the Parent/Child tables and open the Insert/Update Specification section under Table Designer)
If I delete a row from Child, again, no problem.
If I delete a row from Parent, ALL the rows of the child table are deleted, even through most of them point to other parentIDs.
I inherited this DB and all it's tables. Is there some properties settings I'm missing? From what I've read, the cascade delete should ONLY delete the child rows that point to the single parentID I deleted from Parent.
Thanks.
Ben

Right, the delete should only delete rows related to the deleted "parent".
Take a look at the cascading delete setup, and also look for triggers that may be incorrectly written.

Try setting SetNull instead of cascade, which results setting your child table column (where Parent Table's key exit) to NULL.

Related

using a trigger to delete all referenced all IDs referenced to an ID

pls guys...is there a way delete all iDs referenced to particular ID in a database when that particular ID is deleted?
take for instance i have a company data that has list of departments with staff under them and also all those staff have different records under them like attendance, bio data, salary scheme e.t.c.
the way i designed my database is that staffs under a department are referenced to that department using a foreign key and like wise all records under a particular staff is referenced to that staff using a foreign key.
now, is it possible to have a sort of trigger or any other sort of mechanism so that when i delete a staff from the staffs table every other record referenced to that staff will be deleted also.
i would have considered using multi table delete but since am using java sqlite, it doesnt support that from what i read. And i wouldnt like to go through the stress of having to delete all records one after the other from all the tables.
thanks a lot guys
ON DELETE CASCADE could help you. Take a look at the documentation:
CASCADE: A "CASCADE" action propagates the delete or update operation on the parent key to each dependent child key. For an "ON DELETE CASCADE" action, this means that each row in the child table that was associated with the deleted parent row is also deleted.
you just need to reference the row id of the parent table:
CREATE TABLE parentTable(
parent_id INTEGER PRIMARY KEY,
data TEXT
);
CREATE TABLE childTable(
child_id INTEGER,
parent_id INTEGER REFERENCES parentTable(parent_id) ON DELETE CASCADE
);
and I think you would also need to active the foreign keys for this to work:
PRAGMA foreign_keys = ON;

oracle - integrity constraint violated - child record found

I have a huge pl/sql stored procedure, where we make some deletions as long as insertions.
Procedure starts with the statement
EXECUTE IMMEDIATE 'SET CONSTRAINTS ALL DEFERRED'
And at the last commit statement I receive ORA-02292: integrity constraint AAA violated.
The questions is that I don't know which statement exactly causes it, because I have both deletion from parent table (before child one) and insertions into child table before parent.
I tried to google it, but everywhere it's said that 02292 happens when I try to delete only.
Could this error happen when I try to insert value in the child table but there is no this entry in the parent?
Also, what is the difference between 02292 and 02291?
ORA-02292 indicates that the error occurred because A) the constraint has no ON DELETE clause specified, and B) you deleted a row from the master table which had matching references in the child table. Your choices are to modify the constraint so have an ON DELETE CASCADE or to ensure that all child records are deleted before deleting from the master. My preference would be to add ON DELETE CASCADE but I suppose there could be reasons not to do so. See ORA-02292.
ORA-02291 is sort of the opposite of this. ORA-02291 will be raised if you attempt to insert a row into a child table, but the key field values on your new child row as specified in the constraint do not exist in the master table. See ORA-02291.
If you want to disable the constraint from the name to solve ORA-02292.
Look for the table name bounded to that constraint
SELECT owner, table_name FROM dba_constraints WHERE constraint_name = '{CONSTRAINT_NAME}';
Disable constraint (this command should be executed by an admin user)
ALTER TABLE {TABLE_NAME} DISABLE constraint {CONSTRAINT_NAME} cascade;

foreign key data deletion should display error for primary key

i have two tables Table1 and Table2. Where table1 column primary key is referred to table2 column as foreign key.
Now i have to display a error message of constraint violation when ever i delete records from table2 which is having foreign key column of table1.
If I get it right your column A (say) in table 1 references column B (say) in table 2.
What you can do is set the ON DELETE to NO ACTION which will prevent deletion of records from table 2 if any children of it still exists in table 1.
You can can do this by:
ALTER TABLE TABLE1 ADD FOREIGN KEY (A) REFERENCES TABLE2 (B) ON DELETE NO ACTION;
You don't have a constraint violation if you delete records from the child table and not the parent. It is normal to delete child records. For instance if I have a user table and a photos tables that contains the userid from the users table, why would I want to stop that action and throw an error if I want to delete a photo? Deleting a child record doesn't also delete the parent.
If you really want to do that, then you must do it through a trigger (make sure to handle multiple record deletes) or if the FK is a required field, then simply don't grant permissions to delete to the table. Be aware that this may mean you can never delete any records even when you try to delete. A simple method may be to not have a delete function available in the application.
I suspect what you really need to a to get a better definition of what is needed in the requirements document. In over 30 years of dealing with hundreds of databases, I have never seen anyone need this functionality.

how to create triggers in sqlite3?

i am new to this topic.
i want something like this.
i have two tables in my sqliteDatabase one is master and another is child.
Now if i delete a record from master suppose i delete a row from master where id=5, then all the records from the child table whose id = 5 deleted automatically.
I don't know how to create triggers and how to apply foreign key constraints so someone please tell me a way to do this in sqlite3 Manager of firefox.
Thanks
You don't need a trigger for that, your foreign key will do that if you define ON DELETE CASCADE:
CREATE TABLE child(
id INTEGER,
some_info TEXT,
master_id INTEGER,
FOREIGN KEY(master_id) REFERENCES master(id) ON DELETE CASCADE
);
See documentation about foreign keys.
EDIT:
If you really need to do it using a trigger, have a look at Foreing Key Triggers.
This page should help:
http://justatheory.com/computers/databases/sqlite/foreign_key_triggers.html
This is a general trigger reference for SQLite

SQL Server update primary key that's also a foreign key in two tables

I need to update the primary key for a record but it's also the foreign key in two other tables. And I need the updated primary key to be reflected in the child tables as well.
Here is my query and the error:
begin tran
update question set questionparent = 10000, questionid= 10005 where questionid = 11000;
Error 9/4/2009 10:04:49 AM 0:00:00.000 SQL Server Database Error: The UPDATE statement conflicted with the REFERENCE constraint "FK_GoalRequirement_Question". The conflict occurred in database "numgmttest", table "dbo.GoalRequirement", column 'QuestionID'. 14 0
I don't remember how to go about doing this so that's why I'm here. Any help?
Are your relationships using
ON UPDATE CASCADE
If they are then changing the key in the primary table will update the foreign keys.
e.g.
ALTER TABLE Books
ADD CONSTRAINT fk_author
FOREIGN KEY (AuthorID)
REFERENCES Authors (AuthorID) ON UPDATE CASCADE
You may:
disable enforcing FK constraints temporarily (see here or here)
update your PK
update your FKs
enable back enforcing FK constraints
do it all within a transaction and make sure that if transaction fails, you roll it back properly and still enforce the FK constraints back.
But... why do you need to change a PK? I hope this is an action that is executed rarely (legacy data import or something like that).
If you would like to set the Cascade rule graphically then Set Cascade Rule on SQL Management Studio
Open table in design mode
Click Relationship button from top toolbar
Select the required FK relations (one by one)
Right Side - Expand INSERT or UPDATE Specification
Change the UPDATE Rule to - Cascade
Close and Save, Done!
(Tried on SQL 2008)
As I'm not too confident disabling FK constraints, I prefer too :
Duplicate the row with the old PK with one with the new PK
Update the FKs
Delete the row with the old PK
Advantage : No constraint violated during the process.
Go to foreign Key Relations of each child tables and on Insert and Update specification change delete and update rules to cascade.
create a New row with the same data and a different primary key.
update all the children tables.
remove the row that you repeated its data
And its done.

Resources