2011-01-07 48 views
0

,你會寫什麼SQL查詢來獲得具有特定的外鍵的表名的表名。SQL查詢來獲取它們使用特定的列作爲外鍵

Eg. Person_Table(person_id,name,address,...) 
    Purchases_Table(purchaseid, purchased_by_id(fkey)....) 
    AccountDetails_Table(AccountId,PersonID,....) 
    Roles_Table(PersonId,RoleID) 

現在我想找到人名id用作外鍵的表名。 上述模式將返回我

Purchases_Table,AccountDetails_Table, Roles_Table 

數據庫:SQL服務器

+2

哪個數據庫? – Ronnis 2011-01-07 22:30:02

回答

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' 
0

對於PostgreSQL,你可以做這樣的事情:(!從2000)

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)); 

this post處理PostgreSQL郵件列表。