我想知道是否有任何系统SP或任何其他方法来查找数据库中的所有表,这些表使用特定的查找表。我知道我可以一桌一桌地找出来,但我想知道是否有更简单的方法。
感谢
答案 0 :(得分:1)
select OBJECT_NAME(parent_object_id), OBJECT_NAME(referenced_object_id)
from sys.foreign_keys
where parent_object_id = object_id('SchemaName.LookupTableName')
我不是百分百肯定我明白你想要关系到哪个方向,所以你可能会想要这个。
select OBJECT_NAME(parent_object_id), OBJECT_NAME(referenced_object_id)
from sys.foreign_keys
where referenced_object_id = object_id('SchemaName.LookupTableName')
答案 1 :(得分:0)
这是Pinal Dave的a blog post,它有一个冗长的查询来检查系统表以确定FK约束......
SELECT
K_Table = FK.TABLE_NAME,
FK_Column = CU.COLUMN_NAME,
PK_Table = PK.TABLE_NAME,
PK_Column = PT.COLUMN_NAME,
Constraint_Name = C.CONSTRAINT_NAME
FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS C
INNER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS FK ON C.CONSTRAINT_NAME = FK.CONSTRAINT_NAME
INNER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS PK ON C.UNIQUE_CONSTRAINT_NAME = PK.CONSTRAINT_NAME
INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE CU ON C.CONSTRAINT_NAME = CU.CONSTRAINT_NAME
INNER JOIN (
SELECT i1.TABLE_NAME, i2.COLUMN_NAME
FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS i1
INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE i2 ON i1.CONSTRAINT_NAME = i2.CONSTRAINT_NAME
WHERE i1.CONSTRAINT_TYPE = 'PRIMARY KEY'
) PT ON PT.TABLE_NAME = PK.TABLE_NAME
---- optional:
ORDER BY
1,2,3,4
WHERE PK.TABLE_NAME='something'WHERE FK.TABLE_NAME='something'
WHERE PK.TABLE_NAME IN ('one_thing', 'another')
WHERE FK.TABLE_NAME IN ('one_thing', 'another')
答案 2 :(得分:0)
基本思路是你想知道哪些表在相关表中有外键。
select tchild.table_name,tparent.table_name
from information_schema.table_constraints tchild
join information_schema.referential_constraints ref
ON tchild.constraint_name = ref.constraint_name
JOIN information_schema.table_constraints tparent
ON ref.unique_constraint_name = tparent.constraint_name
where tchild.constraint_type = 'FOREIGN KEY'
AND tparent.table_name = '......'
不用最后一个where子句来获取所有东西。