Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A way to check if foreign key exists in SQL 2005

People also ask

How do you check if a foreign key exists in a table in SQL?

You can use the OBJECTPROPERTY() function in SQL Server to check whether or not a table has one or more foreign key constraints. To do this, pass the table's object ID as the first argument, and TableHasForeignKey as the second argument.

How do I check if a foreign key is enabled in SQL Server?

foreign_keys, as well as enabling the constraint. So to see which foreign keys are enabled or disabled, you can check the sys. foreign_keys table on 2005. It has a is_disabled column that has the value of 1 if the foreign key is disabled.

How do I find a foreign key in a database?

A FOREIGN KEY is a field (or collection of fields) in one table, that refers to the PRIMARY KEY in another table. The table with the foreign key is called the child table, and the table with the primary key is called the referenced or parent table.


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]'))
BEGIN
    -- do stuff
END

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.


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)