我有一个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 Studio运行时会显示错误。是否可以在应用密钥之前添加查询以检查密钥是否存在?有一个更好的方法吗?这必须适用于MS SQL 2005和2008。
答案 0 :(得分:11)
使用OBJECT_ID功能测试是否存在。
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;
答案 1 :(得分:1)
您可以通过查看sys.foreign_keys object catalog view:
来检查是否存在外键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