A way to check if foreign key exists in SQL 2005

后端 未结 2 1692
伪装坚强ぢ
伪装坚强ぢ 2021-02-01 13:20

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.

2条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-02-01 14:07

    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)
    

提交回复
热议问题