Deleting rows of a table that has a foreign key to other table - sql

I have folders table and docs table and folders_docs table that maps each doc to one folder. So I try to delete some row from folder table but of course it gives an error like:" Cannot delete or update a parent row: a foreign key constraint fails "
How can cope with that problem?
Thanks in advance...

You can improve the use of REFERENTIAL INTEGRITY in which you define constraints (foreign keys) and propagate the folders deletion to folders_docs and then to docs, but in your case you must play attention at your design: you have a N:M relation between folders and docs, so with a folder deletion you should stop the propagation at the folders_docs table, otherwise you won't be able to find docs in other folders if referenced.
What SQL product are you using?
In many SQL products (SQL Server for example) you can add the ON DELETE CASCADE clause to the ADD CONSTRAINT part of the ALTER TABLE DDL to accomplish this.

got to the database diagram --> relationship properties --> Insert And Update Specification and put both Delete Rule and Update Rule as Cascade, this will let you delete the related rows in another table automatically.

You can add a column folder in the docs table and don't use the folders_docs
You save the management of one table if relationship is 1:n

Related

Alternative of Cascade Delete in SQL Server

I wanted to Delete all the records from all the table where there is reference of my primary table is present.
I know we have Cascade Delete option available where we can create/alter tables to assign cascade delete and perform this,
But I have a very complex data base with huge number of reference tables so I am looking for any alternative or other way I can achieve my target?

Delete Value with Relational Table Trigger vs

How do you delete values with a relational database for connected tables.
Example of Movie Database:
Movie Table -> Movie_has_Genre Table -> Genre Table
If I delete a Movie I would want to delete all the rows of Movie_has_Genre table where the foreign key is the same as the id from the movie table.
Should I be using a Trigger on the Movie table (on delete... do a delete on the relational table) or is there some other built in function to handle this?
I just vaguely recall there was another way to do this but cannot remember what it was called.
You use the cascade delete statement. It's syntax looks like this:
ALTER TABLE dbo.T2
ADD CONSTRAINT FK_T1_T2_Cascade
FOREIGN KEY (keyId) REFERENCES dbo.T1(keyId) ON DELETE CASCADE
The complete syntax is: here
There is an option in SQL Server to do this automatically via CASCADE settings as already shown.
This is a really handy option but make sure you don’t apply it to all of your tables that have foreign key references as it might cause unexpected loss of data. Make sure to thoroughly analyze weather this won’t cause any damage.
Another option is to use multiple delete statements starting from the tables that are referenced first.

TRUNCATE TABLE query unable to execute in SSIS because of foreign key

I have a table Person which contains 2 fields.In my another database i have a Participant Table(also have 2 columns).From Participant Table i have to insert values into Person Table.
but before every insertion,i want truncate the person Table.
I have try it out with linking Execute Sql task to Data flow task.But it is showing error that a Primary Foreign key relation exists there.
If I understand correctly, SSIS has nothing to do with your real problem, which is that you want to truncate a table that is referenced by a foreign key constraint. That question has already been answered: Cannot truncate table because it is being referenced by a FOREIGN KEY constraint?
If a table in sql server has foreign key references then you can't truncate. instead in your execute sql task use delete without a where clause.
delete from person_table
If you are really adamant about truncating the table, you could drop the foreign key constraints, then truncate the table then recreate the foreign key constraints. Providing of course, that the user you are running the package as has the privileges to do so.
Create an "Execute SQl" task and run DELETE FROM person
after this task, run your import.
DELETE FROM will give the same result as TRUNCATE TABLE, but if the table has a foreign key pointing to it, it cant be truncated. You have to use the delete command
You won't be able to delete either unless cascading deletes is turned on (or you delete the child records first). Why is this a problem you ask, why can't I do what I want to do? Because if you do then you may lose the integrity of the data. Suppose I have records in table2 which relate to records in table 1. Suppose further that table1 has an autogenerated id. If I could truncate that table, then I leave those records i ntable 2 hanging out without any record to reference them, they have become orphaned. Well but I'm putting the data back in you say. But then they will have new id numbers and you will still lose the relatinoship tothe related data.
Can you drop the FK and truncate and insert and recreate the FK. Yes you can but it is a poor practice and you should not unless you are also recreating those related records.
The best practice is to use a MERGE statement to update or insert depending on what you need.
In SSIS Transfer SQL Server Objects Task Set Property DeleteFirst to TRUE

SQL Server 2005, Enforce Foreign Key Constraint and Cascade Delete

I am using SQL Server 2005 and I have to relationships going into one table. I had to turn off " Enforce Foreign Key Constraints" because I have 2 relationships going into the same table.
However I want to put cascade delete on.
I thought if I have cascade delete on both of these relationships and if I say deleted something from on of these tables it would cascade and delete into the other table.
However it does not seem to work that way and I am wondering is it because I have the foriegn key constraint off?
If this is the case how can I get around this?
You've gotta have a fk constraint to enforce cascade delete. how sql server know what to delete otherwise?
I'm not clear on why you needed to disable the foreign key constraints in the first place. You can have many relationships to the same table that all enforce referential integrity. However, if you have two relations to the same parent table in the same child table, you can only have cascade update or cascade delete enabled on one of them.
TBH, I cannot think of a situation where I would want a relationship but wouldn't want it enforced. You should always fix the data and enforce the relation so that the data cannot get corrupted.
This is actually a situation where funneling data access through stored procedures helps. If you forced people to only delete through a stored procedure, you could enforce the cascade delete in the procedure without having to enforce in the DRI.
SQL server will not allow multiple cascade paths. To get around this, add 'FOR DELETE' triggers to each additional path.
ALTER TRIGGER [dbo].[trgMyTriggerName] ON [dbo].[tblMyTable] FOR DELETE AS
SET NOCOUNT ON
DELETE FROM tblMySubTable
WHERE MySubTable_Parent_ID IN (SELECT MyTable_ID FROM deleted)
You will still want to add the foreign key, just set 'Enforce Foreign Key Constraint' to No and make your Delete Rule and Update Rule take no action. This allows you to use all the goodness of Foreign Keys (intellisense, Entity framework etc).

Before trigger in SQL Server

I have 2 tables: survey (id(PK), name) and survey_to_topic (survey_id(PK,FK,not null), topic_id(PK,FK,not null)). When I try to delete from survey table, I get exception:
"The DELETE statement conflicted with
the REFERENCE constraint
"FK_survey _to _topic _survey". The
conflict occurred in database
"mydatabase", table
"dbo.survey _to _topic", column
'survey _id'."
So to get no error first I must delete record from table survey_to_topic and after that from table survey. I think it is better to do with before trigger on table survey, but I can't find any information about this. There are a lot of articles about before triggers in PL/SQL, but I use SQL Server.
You can add ON DELETE CASCADE to the relationship between the two tables, and the records from the survey_to_topic table will be deleted automatically.
See http://msdn.microsoft.com/en-us/library/aa933119(SQL.80).aspx
You can use ON DELETE CASCADE. This is added to the table containing the FK.
See example here.
As Alex Deem and astander already mentioned - you should use ON DELETE CASCADE on your foreign key relationship - that handles this scenario automatically for you.
SQL Server doesn't know the concept of BEFORE (operation) TRIGGERs - SQL Server has AFTER triggers, or then INSTEAD OF triggers. See the Introduction to triggers article for some background info.
But ON DELETE CASCADE is definitely the easiest way to do this.
As everyone else here mentioned, ON DELETE CASCADE is a way to go -- as long as you are aware of consequences; there is a reason why ON DELETE NO ACTION (raise error) is the default. In other words, you should plan your deletion strategy -- it is too easy to wipe out rows from several tables unintentionally by using ON DELETE CASCADE.