Delete Value with Relational Table Trigger vs - sql

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.

Related

drop all constraints in a postgresql table - drop cascade

I have 21 tables in my database. However, there are some issues with the table schema (as we are trying to improve our data model). I already referred this post but it is for SQL server.
Currently, just for validation purpose, I would like to upload data inside them.
However, some ill-defined constraints are causing trouble.
So, I would like to delete all constraints only (from all tables) like Foreign key, check , unique, PK, Index etc.
How can I do this?
Currently I tried the below
ALTER TABLE subject
DROP CONSTRAINT subject_details_pk CASCADE;
ALTER TABLE subject
DROP CONSTRAINT subject_foreign_fk CASCADE;
As you can see, I have to write line by line across different tables (and manually find out which table is parent and which table is child etc).
So, is there any other way to drop all constraints in a table? Like Drop cascade ?
Can help me with this?

Adding foreign key fails unless data is first removed and reinserted after

I have an odd issue with foreign keys. I am trying to perform the following query:
ALTER TABLE [GroupMember] FOREIGN KEY ([Group]) REFERENCES [Group]([GUID])
Which gives me the following error:
The ALTER TABLE statement conflicted with the FOREIGN KEY constraint "FK__GroupMember__Group__0D25C822". The conflict occurred in database "x", table "dbo.Group", column 'GUID'.
I then verified the existing things, which I have confirmed are all ok:
Referenced table (dbo.Group) has a defined PRIMARY KEY on [GUID] column
Referencing table (dbo.GroupMember) has no [Group]-values which do not exist in [GUID]-column of dbo.Group-table
No similarly referencing foreign keys exist already
From here on, I experimented. Taking some rows in and out, wiping the table, truncating the table. What I can conclude so far:
If I wipe the referencing table using DELETE FROM [GroupMember]; then try to apply the FK constraint, I receive the same error message
If I truncate the referencing table using TRUNCATE TABLE [GroupMember];, I can apply the FK constraint without errors. Additionally, I am able to reinsert the exact same data after applying the FK constraint, without problems.
From this I can conclude that the data itself is not the problem. Can anyone make sense of this? Why am I able to apply the constraint after truncating the table, but not after deleting all records?
If you are using Microsoft SSMS check whether unchecking "Prevent saving changes that require table re-creation" solves the problem. You'll find this in Options > Designers > Table and Database Designers.
I have had similar issues that have been resolved by this. Let me know if it works or not.
Good luck.

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

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

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

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.