简体   繁体   English

一种检查SQL 2005中是否存在外键的方法

[英]A way to check if foreign key exists in SQL 2005

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. 我正在编写一个脚本,只有当它不存在时才会添加外键。

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. 如果展开表并右键单击现有FK并选择脚本键为“DROP TO”,则可以执行此操作,然后您将从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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM