Delete data with SQL constraints - sql-server

I have the following:
DELETE FROM ContactBase
DELETE FROM AccountBase
It errors with:
The DELETE statement conflicted with the REFERENCE constraint "account_primary_contact". The conflict occurred in database "BMBLANK_MSCRM", table "dbo.AccountBase", column 'PrimaryContactId'.
The DELETE statement conflicted with the REFERENCE constraint "account_contacts". The conflict occurred in database "BMBLANK_MSCRM", table "dbo.ContactBase", column 'AccountId'.
I understand because of the constraint I need to delete the data in a particular order, but if I reverse it:
DELETE FROM AccountBase
DELETE FROM ContactBase
It just reverses the error messages:
The DELETE statement conflicted with the REFERENCE constraint "account_contacts". The conflict occurred in database "BMBLANK_MSCRM", table "dbo.ContactBase", column 'AccountId'.
The DELETE statement conflicted with the REFERENCE constraint "account_primary_contact". The conflict occurred in database "BMBLANK_MSCRM", table "dbo.AccountBase", column 'PrimaryContactId'.
How do I empty these tables?
Thanks

First drop the constraints , delete the data and add them again:
ALTER TABLE AccountBase
DROP CONSTRAINT account_contacts;
ALTER TABLE ContactBase
DROP CONSTRAINT account_primary_contact;
DELETE FROM ContactBase;
DELETE FROM AccountBase;
ALTER TABLE AccountBase
ADD FOREIGN KEY (account_contacts)
REFERENCES ContactBase(PrimaryContactId);
ALTER TABLE ContactBase
ADD FOREIGN KEY (account_primary_contact)
REFERENCES AccountBase(AccountId);
Maybe I mixed them, its confusing without the tables DDL's , so if I did just adjust it.

You can generate a script of the constraints, drop the constraints, delete from tables, then use the script to recreate the constraints.
How to generate all constraints scripts

Drop the constraints and then delete the data from the tables. Then, if needed, add the constraints again.

Related

SQLServer Foreign Key Checks Disabled But Still Can't Drop Table

I have a SQLServer database which I want to drop a table from. The table has FK constraints, but in this case it doesn't matter because when I repopulate the table, the FKs will be replaced correctly.
I've done EXEC sp_msforeachtable "ALTER TABLE ? NOCHECK CONSTRAINT all" which gives a message: sp_msforeachtable "ALTER TABLE ? NOCHECK CONSTRAINTS all" succeded, but when I try to drop my table I get the following SQL error: SQL Error: Could not drop object 'myTable' because ti is referenced by a FOREIGN KEY constraint.
Should the command not have affected my entire database and allowed me to drop the table without an issue? I've also tried doing EXEC sp_msforeachtable "ALTER TABLE myTable NOCHECK CONSTRAINT all" which results in the same error.
NOCheck disable the constraints so they won't be enforced. This would allow you to delete the data without violating the constraint.
Dropping the table would make the constraint definition invalid. You can't have a constraint that references a table that doesn't exist. You wouldn't be able to drop the referenced column from the table either while the constraint exists.
If you will be repopulating the table, just delete the table data and reload it. If you absolutely must drop and recreate the table, you'll need to include the drop & create statements for your foreign key constraints as well.
Note that if you disable the constraint, you'll need to enable using WITH CHECK CHECK (yes twice). The first check turns the constraint on for new data, the second tells SQL to validate the existing data. If you only do one, new data will be checked, but the existing data will not be 'TRUSTED', which can affect how SQL will leverage the FK reference in queries.
Should the command not have affected my entire database and allowed me
to drop the table without an issue?
No. It doesn't matter what the NOCHECK state is; if there are FK constraints that reference a target table, that target table cannot be dropped.
The only way to drop the table is to first drop the FK constraints that reference it.

Update even though using constraints

I'm trying to update a value (small spelling error) in the SQL Server 2014 database.
I do like this:
update t_Table set funID = 'References' where funID = 'Referencies'
When doing this I get the error
The UPDATE statement conflicted with the FOREIGN KEY constraint "FK_t_Table_Language_t_Table". The conflict occurred in database "db", table "dbo.t_Table".
If updating the foreign key, I get a similar error.
Is there any way to update all values at the same time?
I have a vague memory of someone showing a way to do this in management studio but I do not recall how.
Enable update cascade on the foreign key
ALTER TABLE t_Table_Language DROP CONSTRAINT FK_t_Table_Language_t_Table
ALTER TABLE t_Table_Language ADD CONSTRAINT FK_t_Table_Language_t_Table
FOREIGN KEY (funID) REFERENCES t_Table(funID)
ON UPDATE CASCADE
EDIT:
Or the other way around, i'm not sure which table has the foreing key
ALTER TABLE t_Table DROP CONSTRAINT FK_t_Table_Language_t_Table
ALTER TABLE t_Table ADD CONSTRAINT FK_t_Table_Language_t_Table
FOREIGN KEY (funID) REFERENCES t_Table_Language(funID)
ON UPDATE CASCADE
Then do the update on the referenced table (the master table).
UPDATE t_Table_Language
SET funID = 'References'
WHERE funID = 'Referencies'

Adding constraint conflicts with itself, even though it doesn't exist yet

I'm adding delete cascading to a Table. The Clone table has a column DeviceID that is a foreign key to the Device table's DeviceID column. So the SQL script drops the original FK constraint, and attempts to add the new one:
IF EXISTS
(
SELECT *
FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
WHERE CONSTRAINT_NAME = 'FK_Clone_Device'
)
BEGIN
ALTER TABLE Clone
DROP CONSTRAINT FK_Clone_Device
END
IF NOT EXISTS
(
SELECT *
FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
WHERE CONSTRAINT_NAME = 'FK_Clone_Device_Cascade'
)
BEGIN
ALTER TABLE Clone
ADD CONSTRAINT FK_Clone_Device_Cascade
FOREIGN KEY (DeviceID) REFERENCES Device(DeviceID) ON DELETE CASCADE
END
When I run this script, I get the following error:
The ALTER TABLE statement conflicted with the FOREIGN KEY constraint "FK_Clone_Device_Cascade". The conflict occurred in database "DevelopmentDB", table "dbo.Device", column 'DeviceID'.
Maybe I'm misunderstanding the error message, but it sounds like it's conflicting with itself. I'm confused that it happened on the Device table though.
There is an index in the Clone table on DeviceID. Would that matter?
This is on SQL SERVER R2 (Azure)
Sounds like you currently have data in the table that would violate the FK you are trying to create. One way to test this is to add "WITH (NOCHECK)" to the ALTER TABLE statement and see if it lets you create the constraint.
If it does let you create the constraint with NOCHECK, you can either leave it that way and the constraint will only be used to test future inserts/updates, or you can investigate your data to fix the FK violations.
So your example would be:
ALTER TABLE Clone WITH NOCHECK
ADD CONSTRAINT FK_Clone_Device_Cascade
FOREIGN KEY (DeviceID) REFERENCES Device(DeviceID) ON DELETE CASCADE

Oracle drop constraint cascade equivalent in Sql Server

In Oracle, to drop the constraint PK_SAI I use the syntax:
ALTER TABLE "SAISIE"
DROP CONSTRAINT "PK_SAI" CASCADE;
What is the equivalent of this in SQL Server?
You are thinking of the CASCADE feature on FOREIGN KEY constraints, in relation to actual DELETE statements.
ALTER TABLE t2 add constraint FK_T2 foreign key(t_id) references t(id)
ON DELETE CASCADE;
Dropping a constraint with CASCADE does not delete any rows.
DELETE deletes rows, if you have enabled ON DELETE CASCADE.
Dropping the constraint simply drops the constraint (and associated indexes and dependent constraints), not data rows. In SQL Server ALTER TABLE ... I am not aware that there is a "CASCADE" option as in Oracle.
From Oracle docs http://docs.oracle.com/cd/B28359_01/server.111/b28286/statements_3001.htm#i2103845 for the ALTER TABLE statement:
CASCADE Specify CASCADE if you want all other integrity constraints that depend on the dropped integrity constraint to be dropped as well.

How to recheck primary/foreign key constraint for data already in the table in sql server?

I have a table in SQL Server 2005 with a foreign key and it was disable for huge data loading, and then re-enabled:
Example:
alter table table1 nocheck constraint fk_1
go
lots of inserts...
go
alter table table1 check constraint fk_1
go
Now, the question: is there a way to re-check this just inserted data?
The syntax looks a little silly with the word "check" repeated, but what you want is:
alter table table1 with check check constraint fk_1
go
Adding the "with check" option will validate existing data against the constraint. Doing this will also prevent the constraint from becoming untrusted.
If any existing data violates the constraint, you'll get an error that will look like this:
The ALTER TABLE statement conflicted with the CHECK constraint "fk_1".

Resources