I need to add a constraint to an existing SQL server table but only if it does not already exist.
I am creating the constraint using the following SQL.
ALTER TABLE [Foo] ADD CONSTRAINT [FK_Foo_Bar] FOREIGN KEY ([BarId]) REFERENCES [Bar] ([BarId]) ON UPDATE CASCADE ON DELETE CASCADE
I’m hoping I can add some SQL to the begining of the SQL to test for the existence of the constraint but I have no idea how.
Personally I would drop the existing constraint, and recreate it – in case the one that is already there is in some way different
The current, more modern, code I am using is:
not sure if there is any advantage of checking sys.objects … or sys.foreign_keys … but at some point I decided on sys.foreign_keys
Starting with SQL2016 new ‘IF EXISTS’ syntax was added which is a lot more readable: