nocheck
外国の制約を設定して再度有効にした後、奇妙な問題が発生しました。
で使用されたものと同じ古い実行プランを取得してnocheck
います。
次のステートメントでチェックを再度追加した後でも、SQLサーバーが外部制約FKBtoA
が無効になっているように実行プランを生成するのはなぜですか?
alter table B check constraint FKBtoA
[UPDATE1]
これまでのところ、外部制約を削除して再読み込みすることは機能していました。
alter table B drop constraint FKBtoA
alter table B add constraint FKBtoA foreign key (AID) references A(ID)
しかし、本当に大きなテーブルの場合、これはやり過ぎのようです-より良い方法はありますか?
[答え]
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
これは、各ステートメントごとの実行プランのスクリーンショットです。
外部キー制約を無効にする前
外部キー制約を無効にした後
外部キー制約を再度有効にした後