Last active
March 17, 2020 08:02
-
-
Save EitanBlumin/fa4bdeb0cbf84674f1841d40369e930b to your computer and use it in GitHub Desktop.
Find and check untrusted Foreign Keys in all active databases (more info: https://eitanblumin.com/2018/11/06/find-and-fix-untrusted-foreign-keys-in-all-databases/ )
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
IF OBJECT_ID('tempdb..#tmp') IS NOT NULL DROP TABLE #tmp; | |
CREATE TABLE #tmp (DBName SYSNAME, SchemaName SYSNAME, TableName SYSNAME, FullTableName AS QUOTENAME(SchemaName) + N'.' + QUOTENAME(TableName), UntrustedObject SYSNAME); | |
INSERT INTO #tmp(DBName, SchemaName, TableName, UntrustedObject) | |
EXEC sp_MSforeachdb 'IF EXISTS (SELECT * FROM sys.databases WHERE state_desc = ''ONLINE'' AND name = ''?'' AND DATABASEPROPERTYEX(''?'', ''Updateability'') = ''READ_WRITE'') | |
BEGIN | |
USE [?]; | |
SELECT ''?'', OBJECT_SCHEMA_NAME(parent_object_id), OBJECT_NAME(parent_object_id), [name] | |
FROM [?].sys.foreign_keys | |
WHERE is_not_trusted = 1 AND is_not_for_replication = 0 AND is_disabled = 0; | |
END' | |
SELECT | |
* | |
, CommandToRemediate = N'USE ' + QUOTENAME(DBName) + N'; ALTER TABLE ' + FullTableName + N' WITH CHECK CHECK CONSTRAINT ' + QUOTENAME(UntrustedObject) + N';' | |
FROM #tmp | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment