您将编写什么SQL查询来获取具有特定外键的表名。
Eg. Person_Table(person_id,name,address,...)
Purchases_Table(purchaseid, purchased_by_id(fkey)....)
AccountDetails_Table(AccountId,PersonID,....)
Roles_Table(PersonId,RoleID)
现在我想找到Person id用作外键的表名。 上面的架构会给我回复
Purchases_Table,AccountDetails_Table, Roles_Table
数据库:SQL Server
答案 0 :(得分:2)
select OBJECT_NAME(fkc.parent_object_id) as TableName
from sys.foreign_key_columns fkc
inner join sys.columns c
on fkc.referenced_object_id = c.object_id
and fkc.referenced_column_id = c.column_id
where fkc.referenced_object_id = OBJECT_ID('dbo.Person_Table')
and c.name = 'person_id'
答案 1 :(得分:0)
对于postgresql,你可以这样做:
SELECT pt.tgargs, pt.tgnargs, pt.tgdeferrable, pt.tginitdeferred,
pg_proc.proname, pg_proc_1.proname FROM pg_class pc,
pg_proc pg_proc, pg_proc pg_proc_1, pg_trigger pg_trigger,
pg_trigger pg_trigger_1, pg_proc pp, pg_trigger pt
WHERE pt.tgrelid = pc.oid AND pp.oid = pt.tgfoid
AND pg_trigger.tgconstrrelid = pc.oid
AND pg_proc.oid = pg_trigger.tgfoid
AND pg_trigger_1.tgfoid = pg_proc_1.oid
AND pg_trigger_1.tgconstrrelid = pc.oid
AND ((pc.relname= '<< DB_NAME >>')
AND (pp.proname LIKE '%%ins')
AND (pg_proc.proname LIKE '%%upd')
AND (pg_proc_1.proname LIKE '%%del')
AND (pg_trigger.tgrelid=pt.tgconstrrelid)
AND (pg_trigger_1.tgrelid = pt.tgconstrrelid));
请参阅Postgresql邮件列表上的this post(来自2000!)。