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

后端 未结 6 1177
醉梦人生
醉梦人生 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 21:50

    I found a reasonable(ish) way to do it by making SQL write the SQL to drop the constraints:

    select concat("alter table ", table_name, " drop ", constraint_type ," ", constraint_name, ";")
      from information_schema.table_constraints 
      where table_name like 'somefoo_%' 
            and 
            constraint_type <> "PRIMARY KEY";
    

    You will want to modify the table name to suit your needs, or possibly select against other column/values.

    Also, this would select any non primary key constraint, which might be too big of a sledgehammer. Maybe you need to just set it to =?

    I am not a DBA. there may be better ways to do this, but it worked well enough for my purposes.

提交回复
热议问题