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

前端 未结 6 1232
醉酒成梦
醉酒成梦 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 code retrieves all foreign keys that are marked 'WITH NOCHECK' and then uses an ALTER statement to fix them up:

    -- configure cursor on all FKs with "WITH NOCHECK"
    DECLARE UntrustedForeignKeysCursor CURSOR STATIC FOR
        SELECT  f.name,
                t.name 
        FROM    sys.foreign_keys AS f
                LEFT JOIN sys.tables AS t 
                    ON f.parent_object_id = t.object_id 
        Where   Is_Not_Trusted = 1
    OPEN UntrustedForeignKeysCursor
    
    -- loop through the untrusted FKs
    DECLARE @FKName varchar(100)
    DECLARE @TableName varchar(100)
    FETCH NEXT FROM UntrustedForeignKeysCursor INTO @FKName, @TableName
    WHILE @@FETCH_STATUS = 0
    BEGIN
    
        -- Rebuild the FK constraint WITH CHECK
        EXEC ('ALTER TABLE ' + @TableName + ' WITH CHECK CHECK CONSTRAINT ' + @FKName)
    
        -- get next user
        FETCH NEXT FROM UntrustedForeignKeysCursor INTO @FKName, @TableName
    
    END
    
    -- cleanup
    CLOSE UntrustedForeignKeysCursor
    

提交回复
热议问题