views:

4508

answers:

2

I can drop a table if it exists using the following code but do not know how to do the same with a constraint:

IF EXISTS(SELECT 1 FROM sys.objects WHERE OBJECT_ID = OBJECT_ID(N'TableName') AND type = (N'U')) DROP TABLE TableName
go

I also add the constraint using this code:

ALTER TABLE [dbo].[TableName] 
  WITH CHECK ADD CONSTRAINT [FK_TableName_TableName2] FOREIGN KEY([FK_Name])
    REFERENCES [dbo].[TableName2] ([ID])
go
+12  A: 
IF EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'dbo.FK_TableName_TableName2') AND parent_object_id = OBJECT_ID(N'dbo.TableName'))

ALTER TABLE [dbo.TableName] DROP CONSTRAINT [FK_TableName_TableName2]
James L
@TopBanana: you should add the schema 'dbo.'
Mitch Wheat
..and the missing 2 from the constraint name ;-)
Mitch Wheat
its the if exists bit i am really after.. sorry. i'll update my question so it's more clear!
solrev
Sorry John missed that bit, I'll update my answer
James L
cheers thats the one!
solrev
+2  A: 
ALTER TABLE [dbo].[TableName]
    DROP CONSTRAINT FK_TableName_TableName2
Mitch Wheat