How to list out all Foreign Keys with “WITH NOCHECK” in SQL Server

前端 未结 6 1235
醉酒成梦
醉酒成梦 2020-12-13 17:42

Does anyone know a query for listing out all foreign keys in a database with WITH NOCHECK description applied to it? (removing them will boost performance and

6条回答
  •  醉话见心
    2020-12-13 18:07

    The following script will generate the alter statements that will both check existing data and prevent any new violations for foreign keys that are not currently trusted ('with nocheck').

    Execute it in SQL Server Management Studio to generate the scripts and then copy them into a query window to execute them.

    select
        'alter table ' + quotename(s.name) + '.' + quotename(t.name) + ' with check check constraint ' + fk.name +';'
    from 
        sys.foreign_keys fk
    inner join
        sys.tables t
    on
        fk.parent_object_id = t.object_id
    inner join
        sys.schemas s
    on
        t.schema_id = s.schema_id
    where 
        fk.is_not_trusted = 1
    

提交回复
热议问题