MySQL DROP all tables, ignoring foreign keys

前端 未结 24 2785
醉梦人生
醉梦人生 2020-12-02 03:44

Is there a nice easy way to drop all tables from a MySQL database, ignoring any foreign key constraints that may be in there?

24条回答
  •  醉酒成梦
    2020-12-02 03:57

    I use the following with a MSSQL server:

    if (DB_NAME() = 'YOUR_DATABASE') 
    begin
        while(exists(select 1 from INFORMATION_SCHEMA.TABLE_CONSTRAINTS where CONSTRAINT_TYPE='FOREIGN KEY'))
        begin
             declare @sql nvarchar(2000)
             SELECT TOP 1 @sql=('ALTER TABLE ' + TABLE_SCHEMA + '.[' + TABLE_NAME + '] DROP CONSTRAINT [' + CONSTRAINT_NAME + ']')
             FROM information_schema.table_constraints
             WHERE CONSTRAINT_TYPE = 'FOREIGN KEY'
             exec (@sql)
             PRINT @sql
        end
    
        while(exists(select 1 from INFORMATION_SCHEMA.TABLES))
        begin
             declare @sql2 nvarchar(2000)
             SELECT TOP 1 @sql2=('DROP TABLE ' + TABLE_SCHEMA + '.[' + TABLE_NAME + ']')
             FROM INFORMATION_SCHEMA.TABLES
            exec (@sql2)
            PRINT @sql2
        end
    end
    else
        print('Only run this script on the development server!!!!')
    

    Replace YOUR_DATABASE with the name of your database or remove the entire IF statement (I like the added safety).

提交回复
热议问题