How can I drop a table if there is a foreign key constraint in SQL Server?

后端 未结 8 1318
陌清茗
陌清茗 2020-12-15 17:43

I have the following:

DROP TABLE [dbo].[ExtraUserInformation];
DROP TABLE [dbo].[UserProfile];
DROP TABLE [dbo].[webpages_Membership];
DROP TABLE [dbo].[webp         


        
相关标签:
8条回答
  • 2020-12-15 18:13

    Type this .... SET foreign_key_checks = 0;
    delete your table then type SET foreign_key_checks = 1;

    MySQL – Temporarily disable Foreign Key Checks or Constraints

    0 讨论(0)
  • 2020-12-15 18:14

    BhupeshC and murat , this is what I was looking for. However @SQL varchar(4000) wasn't big enough. So, small change

    DECLARE @cmd varchar(4000)
    
    DECLARE MY_CURSOR CURSOR 
      LOCAL STATIC READ_ONLY FORWARD_ONLY
    FOR 
    
    select 'ALTER TABLE ['+s.name+'].['+t.name+'] DROP CONSTRAINT [' + RTRIM(f.name) +'];' FROM sys.Tables t INNER JOIN sys.foreign_keys f ON f.parent_object_id = t.object_id INNER JOIN sys.schemas s ON s.schema_id = f.schema_id
    
    OPEN MY_CURSOR
    FETCH NEXT FROM MY_CURSOR INTO @cmd
    WHILE @@FETCH_STATUS = 0
    BEGIN
        -- EXEC (@cmd)
        PRINT @cmd
        FETCH NEXT FROM MY_CURSOR INTO @cmd
    END
    CLOSE MY_CURSOR
    DEALLOCATE MY_CURSOR
    
    GO
    
    0 讨论(0)
提交回复
热议问题