The DELETE statement conflicted with the REFERENCE constraint, cascading delete - sql

I want to delete a user form 'dbo.Gebruiker' when I run my query I get this error message.
The DELETE statement conflicted with the REFERENCE constraint
"FK_Klant_Gebruiker_beheerderid". The conflict occurred in database
"Planning", table "dbo.Klant", column 'BeheerderId'.
After reading on the forum, they said that first I have to remove from other table so when I run my query, again I get another message
The DELETE statement conflicted with the REFERENCE constraint
"FK_Gebruiker_Klant". The conflict occurred in database "Planning",
table "dbo.Gebruiker", column 'KlantId'.
When I run this query to see if that columns exists
select * from dbo.Gebruiker where
KlantId='1CA25570-1A02-42FC-836D-4897B95EF44A'
it does not show anything.
After reading on google and on forums they say that first I have to delete the foreign key constraint.
I'm also putting the helpConstraint
What would be best way to delete a user from "dbo.Gebruiker" please?
GebruikerTable and Dependencies
KlantTable and Dependencies

In general terms, if you want to delete a row whose id is a FK in another table and you are not using an automated DELETE rule (like CASCADE), then you need to do something with the rows on the dependent table(s) before the database will allow you to perform the DELETE.
It seems that this your problem, so you need to consider what to do with the rows of the dependent table(s) that currently refer to the key value of the row you intend to delete.

Related

SQL error when trying to delete a row from my table

I have an issue and get this SQL error that I can't identify the source of. It's blocking the delete API and nothing is clear about it on the internet:
The DELETE statement conflicted with the REFERENCE constraint "FK_re". The conflict occurred in database "test", table "dbo.MatchingTable", column 'M_Id'.
The statement has been terminated. The DELETE statement conflicted with the REFERENCE constraint "FK_re". The conflict occurred in database "test", table "dbo.MatchingTable", column 'M_Id'.
The DELETE statement conflicted with the REFERENCE constraint "FK_re"
this means you can't delete what you want to because there is a foreign key reference.
The tables are linked by a piece of data in certain column, and SQL is warning you that if you do that the link will be to nothing.
This is one of the strengths of SQL data integrity.

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.

How to validate data in sql server?

I have an issue related to data in sql server. In my database some of the constraint were not enabled i.e. they were not checked , After some time working on it we found this issue that a parent rows can be deleted without deleting child, which was an issue. I enabled all the constraint in the database using query
ALTER TABLE tbl_name CHECK CONSTRAINT ALL
above query was executed on all the tables of that database without any error . But my concern is whether it will work or not , if it will work on the existing data then what will happen to that data whose parent table data has been deleted.
I want to know is there any way such that I can validate such data data whose parent record doesn't exist in the entire database. There are about 270 constraint containing FOREIGN KEY AND UNIQUE KEY . I don't want to go for manual option.
Please help me out.
ALTER TABLE tbl_name CHECK CONSTRAINT ALL
only re-enables the constraints. Importantly, the constraints are not checked against the existing data in the database (nor are they trusted by the optimizer). If you want that to occur, you need to specify WITH CHECK as well:
ALTER TABLE tbl_name WITH CHECK CHECK CONSTRAINT ALL
(And yes, the word CHECK appears twice)
If you execute this, and there are orphaned child rows (or other invalid constraints), then the ALTER TABLE will fail with an error message. There's nothing SQL Server can do to fix this issue - it's for you to decide whether to a) remove the orphaned rows, or b) to re-create, in some manner, a suitable parent row for them.
You can also add the 'ON DELETE CASCADE' code to the end of foreign keys to prevent orphaned child rows from persisting.
This is more of a 'better practice' going forward than a solution, but I believe Damien_The_Unbeliever has answered your main question.

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

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.