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

后端 未结 6 1182
醉梦人生
醉梦人生 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

    Run the following script to delete all the constraints in all tables under current DB and then run the drop table statements.

    DECLARE @dropAllConstraints NVARCHAR(MAX) = N'';
    
    SELECT @dropAllConstraints  += N'
    ALTER TABLE ' + QUOTENAME(OBJECT_SCHEMA_NAME(parent_object_id))
        + '.' + QUOTENAME(OBJECT_NAME(parent_object_id)) + 
        ' DROP CONSTRAINT ' + QUOTENAME(name) + ';'
    FROM sys.foreign_keys;
    EXEC sp_executesql @dropAllConstraints 
    

提交回复
热议问题