If foreign key exists, drop it

Tavousi picture Tavousi · Feb 8, 2012 · Viewed 9.4k times · Source

I have a table that has a foreign key relation with another table.

I want to check that if this relation exists, drop it.

How to I write this query.

Thanks.

Answer

Iridio picture Iridio · Feb 8, 2012

If you are using SQL Server, this should works

if exists (select 1 from sys.objects where object_id = OBJECT_ID(N'[FKName]') AND parent_object_id = OBJECT_ID('TableName'))
  alter table TableName drop constraint FKName