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

后端 未结 12 2097
盖世英雄少女心
盖世英雄少女心 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:59

    Not quite 1 query, still quite short and sweet:

    -- Disable all referential integrity constraints
    EXEC sp_msforeachtable 'ALTER TABLE ? NOCHECK CONSTRAINT ALL'
    GO
    
    -- Drop all PKs and FKs
    declare @sql nvarchar(max)
    SELECT @sql = STUFF((SELECT '; ' + 'ALTER TABLE ' + Table_Name  +'  drop constraint ' + Constraint_Name  from Information_Schema.CONSTRAINT_TABLE_USAGE ORDER BY Constraint_Name FOR XML PATH('')),1,1,'')
    EXECUTE (@sql)
    GO
    
    -- Drop all tables
    EXEC sp_msforeachtable 'DROP TABLE ?'
    GO
    

提交回复
热议问题