Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

T-SQL: DROP Table cascade constraints equivalent?

Tags:

tsql

cascade

In oracle, I can issue a DROP TABLE ... cascade constraints and it won't complain about FKs, etc.

Is there an equivalent in T-SQL?

like image 333
chris Avatar asked Feb 11 '10 19:02

chris


1 Answers

For those who got here in the hope of a more generally applicable answer

This will find the constraint, drop it, and then the column

Thanks and a vote to Tim Lentine How to find the name of a default constraint for the start.

Declare @sql VarChar(255)
Declare @tableName Varchar(255)
Declare @columnName VarChar(255)
Select @tableName = 'MyTableName'
Select @columnName = 'MyColumnName'
select @sql = o.[name] from sysobjects o 
inner join syscolumns c
on o.id = c.cdefault
inner join sysobjects t
on c.id = t.id
where o.xtype = 'd'
and t.name = @tableName
and c.name = @columnName

if @sql is not null
begin
  select @sql = 'Alter Table ' + @tableName + ' Drop Constraint ' + @sql + ' Alter Table ' + @tablename + ' Drop Column ' + @columnName
  exec(@sql)
end
like image 118
Tony Hopkinson Avatar answered Sep 29 '22 12:09

Tony Hopkinson