在这里阅读MS DOCS之后。
修改外键
若要使用Transact-SQL修改FOREIGN KEY约束,必须首先删除现有的FOREIGN KEY约束,然后使用新定义重新创建它。有关更多信息,请参见删除外键关系和创建外键关系。
如果您相信我,请添加一个新的FK并删除旧的FK。要禁用扫描,您可以使用NO CHECK
选项
--DROP TABLE T2
--DROP TABLE T1
CREATE TABLE T1 (
[Id] INT,
[NAME] varchar(100), CONSTRAINT [PK_T1] PRIMARY KEY CLUSTERED (id))
CREATE TABLE T2 (
t2_id int,
T1_Id INT NOT NULL
,CONSTRAINT [FK_T2_T1] FOREIGN KEY (T1_Id) REFERENCES T1(Id)
)
CREATE UNIQUE NONCLUSTERED INDEX IX_T1_Id ON T1 (Id)
select
ix.index_id,
ix.name as index_name,
ix.type_desc as index_type_desc,
fk.name as fk_name
from sys.indexes ix
left join sys.foreign_keys fk on
fk.referenced_object_id = ix.object_id
and fk.key_index_id = ix.index_id
and fk.parent_object_id = object_id('T2')
where ix.object_id = object_id('T1');
╔══════════╦════════════╦═════════════════╦══════════╗
║ index_id ║ index_name ║ index_type_desc ║ fk_name ║
╠══════════╬════════════╬═════════════════╬══════════╣
║ 1 ║ PK_T1 ║ CLUSTERED ║ FK_T2_T1 ║
║ 2 ║ IX_T1_Id ║ NONCLUSTERED ║ NULL ║
╚══════════╩════════════╩═════════════════╩══════════╝
ALTER TABLE T2
WITH NOCHECK
ADD CONSTRAINT [FK_T2_T1_NEW] FOREIGN KEY(T1_Id)
REFERENCES T1(Id)
select
ix.index_id,
ix.name as index_name,
ix.type_desc as index_type_desc,
fk.name as fk_name
from sys.indexes ix
left join sys.foreign_keys fk on
fk.referenced_object_id = ix.object_id
and fk.key_index_id = ix.index_id
and fk.parent_object_id = object_id('T2')
where ix.object_id = object_id('T1');
╔══════════╦════════════╦═════════════════╦══════════════╗
║ index_id ║ index_name ║ index_type_desc ║ fk_name ║
╠══════════╬════════════╬═════════════════╬══════════════╣
║ 1 ║ PK_T1 ║ CLUSTERED ║ FK_T2_T1 ║
║ 2 ║ IX_T1_Id ║ NONCLUSTERED ║ FK_T2_T1_NEW ║
╚══════════╩════════════╩═════════════════╩══════════════╝
ALTER TABLE T2
DROP CONSTRAINT FK_T2_T1
select
ix.index_id,
ix.name as index_name,
ix.type_desc as index_type_desc,
fk.name as fk_name
from sys.indexes ix
left join sys.foreign_keys fk on
fk.referenced_object_id = ix.object_id
and fk.key_index_id = ix.index_id
and fk.parent_object_id = object_id('T2')
where ix.object_id = object_id('T1');
╔══════════╦════════════╦═════════════════╦══════════════╗
║ index_id ║ index_name ║ index_type_desc ║ fk_name ║
╠══════════╬════════════╬═════════════════╬══════════════╣
║ 1 ║ PK_T1 ║ CLUSTERED ║ NULL ║
║ 2 ║ IX_T1_Id ║ NONCLUSTERED ║ FK_T2_T1_NEW ║
╚══════════╩════════════╩═════════════════╩══════════════╝
看看是否可行,我正在尝试再添加一个FK,以便将新的FK链接到创建的新索引,并删除旧的FK。我知道问题不是要删除现有的问题,而是看看此选项是否对您有帮助。
另外,根据Max Vernon的评论:“ WITH NOCHECK选项将防止外键被优化程序信任。在某些时候,您必须更改外键,以便使用ALTER TABLE来信任外键...有检查”
该NOCHECK
会只在创建的时候被忽略,但执行完整性contraint你在某个时间点运行此。