SQL Server: drop table cascade equivalent? SQL Server: drop table cascade equivalent? sql sql

SQL Server: drop table cascade equivalent?


In SQL Server Management Studio, go to Options / SQL Server Object Explorer / Scripting, and enable 'Generate script for dependent objects'. Then right click the table, script > drop to > new query window and it will generate it for you.


I don't believe SQL has a similarly elegant solution. You have to drop any related constraints first before you can drop the table.

Fortunately, this is all stored in the information schema and you can access that to get your whack list.

This blog post should be able to get you what you need:http://weblogs.asp.net/jgalloway/archive/2006/04/12/442616.aspx

-- t-sql scriptlet to drop all constraints on a tableDECLARE @database nvarchar(50)DECLARE @table nvarchar(50)set @database = 'DatabaseName'set @table = 'TableName'DECLARE @sql nvarchar(255)WHILE EXISTS(select * from INFORMATION_SCHEMA.TABLE_CONSTRAINTS where constraint_catalog = @database and table_name = @table)BEGIN    select    @sql = 'ALTER TABLE ' + @table + ' DROP CONSTRAINT ' + CONSTRAINT_NAME     from    INFORMATION_SCHEMA.TABLE_CONSTRAINTS     where    constraint_catalog = @database and             table_name = @table    exec    sp_executesql @sqlEND


This might be a horrible solution, but I find it's quick. It is similar to Vinnie's answer, but the product of the SQL statement is another series of SQL statements that will delete all constraints and tables.

(select  'ALTER TABLE ' + tc.table_name + ' DROP CONSTRAINT ' + tc.constraint_name + ';'from  INFORMATION_SCHEMA.TABLES t  ,INFORMATION_SCHEMA.TABLE_CONSTRAINTS tcwhere  t.table_name = tc.table_name  and tc.constraint_name not like '%_pk'  and tc.constraint_name not like 'pk_%'  and t.table_catalog='<schema>') UNION (select  'DROP TABLE ' + t.table_name + ';'from  INFORMATION_SCHEMA.TABLES twhere  t.table_catalog='<schema>')