Sqlserver
 SQL >> Database >  >> RDS >> Sqlserver

Come elencare tutte le chiavi esterne con WITH NOCHECK in SQL Server

La query seguente restituisce il nome delle chiavi esterne del database corrente che risultano disabilitate, cioè con WITH NOCHECK.

Per SQL Server 2005/2008:

select * from sys.foreign_keys where is_disabled=1

C'è stata una discussione nella risposta sulla differenza tra "disabilitato" e "non attendibile". Il codice qui sotto chiarisce la distinzione tra is_disabled e is_not_trusted.

-- drop table t1 -- drop table t2 create table t1(i int not null, fk int not null) create table t2(i int not null) -- create primary key on t2 alter table t2 add constraint pk_1 primary key (i) -- create foriegn key on t1 alter table t1 add constraint fk_1 foreign key (fk) references t2 (i) --insert some records insert t2 values(100) insert t2 values(200) insert t2 values(300) insert t2 values(400) insert t2 values(500) insert t1 values(1,100) insert t1 values(2,100) insert t1 values(3,500) insert t1 values(4,500) ---------------------------- -- 1. enabled and trusted select name,is_disabled,is_not_trusted from sys.foreign_keys GO -- 2. disable the constraint alter table t1 NOCHECK CONSTRAINT fk_1 select name,is_disabled,is_not_trusted from sys.foreign_keys GO -- 3. re-enable constraint, data isnt checked, so not trusted. -- this means the optimizer will still have to check the column alter table t1 CHECK CONSTRAINT fk_1 select name,is_disabled,is_not_trusted from sys.foreign_keys GO --4. drop the foreign key constraint & re-add -- it making sure its checked -- constraint is then enabled and trusted alter table t1 DROP CONSTRAINT fk_1 alter table t1 WITH CHECK add constraint fk_1 foreign key (fk) references t2 (i) select name,is_disabled,is_not_trusted from sys.foreign_keys GO --5. drop the foreign key constraint & add but dont check -- constraint is then enabled, but not trusted alter table t1 DROP CONSTRAINT fk_1 alter table t1 WITH NOCHECK add constraint fk_1 foreign key (fk) references t2 (i) select name,is_disabled,is_not_trusted from sys.foreign_keys GO

is_disabled indica che il vincolo è disabilitato.

is_not_trusted indica invece che SQL Server non ha la certezza che i dati siano stati verificati rispetto alla tabella della chiave esterna.

Di conseguenza non puoi dare per scontato che riabilitare il vincolo porti a un'ottimizzazione delle query. Per fare in modo che l'ottimizzatore si fidi della colonna, la soluzione migliore è eliminare il vincolo e ricrearlo con l'opzione WITH CHECK (punto 4).