我有一个包含大量表格(> 100)的Microsoft SQL Server 2012数据库。我还有许多多对多关系表。所有PK / FK关系都在表中进行,以便我知道哪个列属于哪个列或哪些父表或子表列。我想询问是否有可能有一个通用脚本来检查所有这些甚至是给定表,如果有孤立的项目并向我们展示。我的意思是,如果对父项或子项的引用不存在更长时间(某些表的Cascade Delete配置中的错误,我们现在需要检查数据质量:()。
更新
我想我无法正确解释我的要求。我不想看到引用,我想看看是否有任何数据引用子项或子项是引用不再存在的父项。
答案 0 :(得分:0)
Try This for get all constraints :
SELECT OBJECT_NAME(OBJECT_ID) AS NameofConstraint,
SCHEMA_NAME(schema_id) AS SchemaName,
OBJECT_NAME(parent_object_id) AS TableName,
type_desc AS ConstraintType
FROM sys.objects
WHERE type_desc LIKE '%CONSTRAINT'
答案 1 :(得分:0)
试试这个。
SELECT obj.name AS FK_NAME,
sch.name AS [schema_name],
tab1.name AS [table],
col1.name AS [column],
tab2.name AS [referenced_table],
col2.name AS [referenced_column]
FROM sys.foreign_key_columns fkc
INNER JOIN sys.objects obj
ON obj.object_id = fkc.constraint_object_id
INNER JOIN sys.tables tab1
ON tab1.object_id = fkc.parent_object_id
INNER JOIN sys.schemas sch
ON tab1.schema_id = sch.schema_id
INNER JOIN sys.columns col1
ON col1.column_id = parent_column_id AND col1.object_id = tab1.object_id
INNER JOIN sys.tables tab2
ON tab2.object_id = fkc.referenced_object_id
INNER JOIN sys.columns col2
ON col2.column_id = referenced_column_id AND col2.object_id = tab2.object_id