How to drop a list of SQL Server tables, ignoring constraints?

后端 未结 6 1176
醉梦人生
醉梦人生 2021-02-12 21:47

I have a list of half a dozen MSSQL 2008 tables that I would like to remove at once from my database. The data has been entirely migrated to new tables. There is no reference in

6条回答
  •  深忆病人
    2021-02-12 22:14

    It depends on how you want to drop the tables. If list of tables need to drop covers almost above 20 % of tables under your DB.

    Then I will disable all the constraints in that DB under my script and drop the tables and Enable the constraints under the same script.

    --To Disable a Constraint at DB level
    
    EXEC sp_MSForEachTable 'ALTER TABLE ? NOCHECK CONSTRAINT ALL'
    
    --Write the code to DROP tables
    
    DROP TABLE TABLENAME
    
    DROP TABLE TABLENAME
    
    DROP TABLE TABLENAME
    
    --To Enable a Constraint at DB level
    
    EXEC sp_MSForEachTable 'ALTER TABLE ? CHECK CONSTRAINT ALL'
    

    Finally to check the Status of your constraints fire up this Query.

    --Checks the Status of Constraints
    
    SELECT (CASE 
        WHEN OBJECTPROPERTY(CONSTID, 'CNSTISDISABLED') = 0 THEN 'ENABLED'
        ELSE 'DISABLED'
        END) AS STATUS,
        OBJECT_NAME(CONSTID) AS CONSTRAINT_NAME,
        OBJECT_NAME(FKEYID) AS TABLE_NAME,
        COL_NAME(FKEYID, FKEY) AS COLUMN_NAME,
        OBJECT_NAME(RKEYID) AS REFERENCED_TABLE_NAME,
        COL_NAME(RKEYID, RKEY) AS REFERENCED_COLUMN_NAME
    FROM SYSFOREIGNKEYS
    ORDER BY TABLE_NAME, CONSTRAINT_NAME,REFERENCED_TABLE_NAME, KEYNO
    

    If you dont want to disable the constraints at Database level then make a list of tables which you want to drop.

    Step1 : Check the Constraints associated with thos tables

    SELECT * 
    FROM sys.foreign_keys
    WHERE referenced_object_id = object_id('dbo.Tablename')
    

    Step2 : Disable the Constraints which are associated with these tables.

    ALTER TABLE MyTable NOCHECK CONSTRAINT MyConstraint
    

    Step3 : Drop the tables

    DROP TABLE TABLENAME
    

提交回复
热议问题