Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/sql-server/27.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/sql-server-2005/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql server 在使用sql脚本添加外键之前检查外键_Sql Server_Sql Server 2005_Sql Server 2008 - Fatal编程技术网

Sql server 在使用sql脚本添加外键之前检查外键

Sql server 在使用sql脚本添加外键之前检查外键,sql-server,sql-server-2005,sql-server-2008,Sql Server,Sql Server 2005,Sql Server 2008,我有一个向表中添加外键的SQL脚本,如下所示 ALTER TABLE [security].[Pages] WITH NOCHECK ADD CONSTRAINT [FK_Pages_PageClasses] FOREIGN KEY ([PageClassId]) REFERENCES [security].[PageClasses]([PageClassId]) ON DELETE NO ACTION ON UPDATE NO ACTION; 有时表已经有这个外键,所以从Management

我有一个向表中添加外键的SQL脚本,如下所示

ALTER TABLE [security].[Pages] WITH NOCHECK
ADD CONSTRAINT [FK_Pages_PageClasses] FOREIGN KEY ([PageClassId]) REFERENCES [security].[PageClasses]([PageClassId]) ON DELETE NO ACTION ON UPDATE NO ACTION;
有时表已经有这个外键,所以从ManagementStudio运行时会显示错误。在应用密钥之前,是否可以添加查询以检查密钥是否存在?有更好的方法吗?这必须适用于MS SQL 2005和2008。

使用该函数测试是否存在

IF OBJECT_ID('[security].[FK_Pages_PageClasses]') IS NULL
    ALTER TABLE [security].[Pages] WITH NOCHECK
        ADD CONSTRAINT [FK_Pages_PageClasses] FOREIGN KEY ([PageClassId]) REFERENCES [security].[PageClasses]([PageClassId]) ON DELETE NO ACTION ON UPDATE NO ACTION;

您可以通过查看以下内容来检查外键的存在:


这么简单。为什么其他人都发布如此复杂的回复?
IF NOT EXISTS(SELECT * FROM sys.foreign_keys WHERE object_id = object_id(N'[Security].[FK_Pages_PageClasses]') and parent_object_id = object_id(N'[Security].[Pages]'))
BEGIN
    ALTER TABLE [security].[Pages] WITH NOCHECK
    ADD CONSTRAINT [FK_Pages_PageClasses] FOREIGN KEY ([PageClassId]) REFERENCES [security].[PageClasses]([PageClassId]) ON DELETE NO ACTION ON UPDATE NO ACTION;
END