Lookup table usage on DB
I was wondering is there any system SP or any other way to find out all the tables in a DB, which are using a specific lookup table. I know i can go table by table开发者_如何学运维 and find out, but i was wondering if there is any easier way.
thanks
select OBJECT_NAME(parent_object_id), OBJECT_NAME(referenced_object_id)
from sys.foreign_keys
where parent_object_id = object_id('SchemaName.LookupTableName')
I'm not 100% sure I understood which direction you're trying to go with the relationships, so you may want this instead.
select OBJECT_NAME(parent_object_id), OBJECT_NAME(referenced_object_id)
from sys.foreign_keys
where referenced_object_id = object_id('SchemaName.LookupTableName')
Here's a blog post by Pinal Dave with a lengthy query that checks system tables to determine FK constraints...
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')
The basic idea is you want to know which tables have a foreign key into the table in question.
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 = '......'
Leave off that last where clause to get all stuff.
精彩评论