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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/869081/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-01 02:05:35  来源:igfitidea点击:

A way to check if foreign key exists in SQL 2005

sqlsql-server-2005foreign-keys

提问by CodeLikeBeaker

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.

有没有一种简单的方法来检查表中的列是否存在外键?我正在编写一个脚本,只有在外键不存在时才会添加它。

回答by CodeLikeBeaker

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 获得生成的脚本。

回答by ristonj

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)