How to drop all tables from a database with one SQL query?

后端 未结 12 2074
盖世英雄少女心
盖世英雄少女心 2020-12-12 09:44

I don\'t want to type all tables\' name to drop all of them. Is it possible with one query?

12条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-12 09:55

    If you want to use only one SQL query to delete all tables you can use this:

    EXEC sp_MSforeachtable @command1 = "DROP TABLE ?"
    

    This is a hidden Stored Procedure in sql server, and will be executed for each table in the database you're connected.

    Note: You may need to execute the query a few times to delete all tables due to dependencies.

    Note2: To avoid the first note, before running the query, first check if there foreign keys relations to any table. If there are then just disable foreign key constraint by running the query bellow:

    EXEC sp_msforeachtable "ALTER TABLE ? NOCHECK CONSTRAINT all"
    

提交回复
热议问题