Delete data with foreign key in SQL Server table

后端 未结 9 623
青春惊慌失措
青春惊慌失措 2020-12-12 20:32

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

相关标签:
9条回答
  • 2020-12-12 21:29

    SET foreign_key_checks = 0; DELETE FROM yourtable; SET foreign_key_checks = 1;

    0 讨论(0)
  • 2020-12-12 21:31

    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
    
    0 讨论(0)
  • 2020-12-12 21:32

    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.

    0 讨论(0)
提交回复
热议问题