views:

859

answers:

2

Is there an easy way to check if a foreign key exists for a column in a table? I am writing a script which will add the foreign key only if it does not exist.

Thanks

+8  A: 

You can use this script:

IF EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_NAME]') AND parent_object_id = OBJECT_ID(N'[dbo].[MyTable]'))

This can be done if you expand out the table and right click on an existing FK and choose script key as "DROP TO" and then you will get a generated script from SQL.

Hope this helps.

Jason Heine
This script worked great! I can't believe you could script something like that from the menu. Thanks a bunch for the help.
You can pretty much right click just about anything in SQL and have it generate a script for you, Tables, Stored Procedures, Foreign Key and more. Management studio is your friend once you learn some of the cool features it can do.
Jason Heine
+2  A: 

Woo-hoo! I just spent the past two days doing this.

IF NOT EXISTS (SELECT name FROM sys.foreign_keys WHERE name = 'FK_Name')
   ALTER TABLE table_name ADD CONSTRAINT FK_Name FOREIGN KEY (idcol) REFERENCES OtherTable(idcol)
ristonj