题
对于给定的表“foo”,我需要一个查询来生成一组具有指向 foo 的外键的表。我使用的是Oracle 10G。
解决方案
这应该有效(或接近):
select table_name
from all_constraints
where constraint_type='R'
and r_constraint_name in
(select constraint_name
from all_constraints
where constraint_type in ('P','U')
and table_name='<your table here>');
其他提示
以下声明应给予孩子们及其所有后代。我已经在 Oracle 10 数据库上进行了测试。
SELECT level, main.table_name parent,
link.table_name child
FROM user_constraints main, user_constraints link
WHERE main.constraint_type IN ('P', 'U')
AND link.r_constraint_name = main.constraint_name
START WITH main.table_name LIKE UPPER('&&table_name')
CONNECT BY main.table_name = PRIOR link.table_name
ORDER BY level, main.table_name, link.table_name
以下是如何进一步推进 Mike 的查询以获得 列名 从约束名称:
select * from user_cons_columns
where constraint_name in (
select constraint_name
from all_constraints
where constraint_type='R'
and r_constraint_name in
(select constraint_name
from all_constraints
where constraint_type in ('P','U')
and table_name='<your table name here>'));
链接到 Oracle 数据库在线文档
您可能想探索 数据字典视图. 。它们有前缀:
- 用户
- 全部
- 数据库管理员
样本:
select * from dictionary where table_name like 'ALL%'
继续迈克的示例,您可能希望生成脚本来启用/禁用约束。我只修改了第一行中的“选择”。
select 'alter table ' || TABLE_NAME || ' disable constraint ' || CONSTRAINT_NAME || ';'
from all_constraints
where constraint_type='R'
and r_constraint_name in
(select constraint_name
from all_constraints
where constraint_type in ('P','U')
and table_name='<your table here>');
我知道现在回答有点晚了,但无论如何让我回答一下,上面的一些答案非常复杂,因此这里有一个更简单的答案。
`SELECT a.table_name child_table, a.column_name child_column, a.constraint_name, b.table_name parent_table, b.column_name parent_column FROM all_cons_columns a JOIN all_constraints c ON a.owner = c.owner AND a.constraint_name = c.constraint_name join all_cons_columns b on c.owner = b.owner and c.r_constraint_name = b.constraint_name WHERE c.constraint_type = 'R' AND a.table_name = 'your table name'`
select distinct table_name, constraint_name, column_name, r_table_name, position, constraint_type
from (
SELECT uc.table_name,
uc.constraint_name,
cols.column_name,
(select table_name from user_constraints where constraint_name = uc.r_constraint_name)
r_table_name,
(select column_name from user_cons_columns where constraint_name = uc.r_constraint_name and position = cols.position)
r_column_name,
cols.position,
uc.constraint_type
FROM user_constraints uc
inner join user_cons_columns cols on uc.constraint_name = cols.constraint_name
where constraint_type != 'C'
)
start with table_name = '&&tableName' and column_name = '&&columnName'
connect by nocycle
prior table_name = r_table_name
and prior column_name = r_column_name;
下载 Oracle 10G 参考指南,其中解释了数据字典表。
上面的答案很好,但请查看可能与约束相关的其他表格。
SELECT * FROM DICT WHERE TABLE_NAME LIKE '%CONS%';
最后,获取像 Toad 或 SQL Developer 这样的工具,它允许您在 UI 中浏览这些内容,您需要学习使用表格,但也应该使用 UI。
不隶属于 StackOverflow