I\'m going to delete data in an SQL Server table (parent) which has a relationship with another table (child).
I tried the basic Delete query. But it isn\'t working (and
SET foreign_key_checks = 0; DELETE FROM yourtable; SET foreign_key_checks = 1;
Usefull script which you can delete all data in all tables of a database , replace tt with you databse name :
declare @tablename nvarchar(100)
declare c1 cursor for
SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_CATALOG='tt' AND TABLE_TYPE='BASE TABLE'
open c1
fetch next from c1 into @tablename
while @@FETCH_STATUS = 0
begin
print @t1
exec('alter table ' + @tablename + ' nocheck constraint all')
exec('delete from ' + @tablename)
exec ('alter table ' + @tablename + ' check constraint all')
fetch next from c1 into @tablename
end
close c1
DEALLOCATE c1
If you wish the delete to be automatic, you need to change your schema so that the foreign key constraint is ON DELETE CASCADE.
For more information, see the MSDN page on Cascading Referential Integrity Constraints.
ETA (after clarification from the poster): If you can't update the schema, you have to manually DELETE the affected child records first.