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
The more simple solution is provided in Eric Isaacs’s answer. However, it will find constraints on any table. If you want to target a foreign key constraint on a specific table, use this: