【发布时间】:2009-07-04 17:56:04
【问题描述】:
我有一个奇怪的问题,在将 nocheck 设置为外部约束并重新启用它之后,
我得到了与nocheck 相同的过时执行计划。
为什么即使在使用以下语句再次添加检查后,SQL Server 仍会生成一个执行计划,就好像外部约束 FKBtoA 被禁用一样?
alter table B check constraint FKBtoA
[更新1]
到目前为止,放弃外国约束并阅读它是有效的。
alter table B drop constraint FKBtoA
alter table B add constraint FKBtoA foreign key (AID) references A(ID)
但是对于非常大的桌子,这似乎有点过头了 - 有没有更好的方法?
[回答]
我必须在 alter 语句中添加 WITH CHECK 以获取旧的执行计划
alter table B WITH CHECK add constraint FKBtoA foreign key (AID) references A(ID)
这是一个完整的 SQL 语句
create table A ( ID int identity primary key )
create table B (
ID int identity primary key,
AID int not null constraint FKBtoA references A (ID)
)
select *
from B
where exists (select 1 from A where A.ID = B.AID)
alter table B nocheck constraint FKBtoA
GO
select *
from B
where exists (select 1 from A where A.ID = B.AID)
alter table B check constraint FKBtoA
GO
select *
from B
where exists (select 1 from A where A.ID = B.AID)
这是每个SELECT 语句的执行计划截图
禁用外键约束之前
禁用外键约束后
重新启用外键约束后
【问题讨论】:
标签: sql sql-server tsql sql-execution-plan