我需要在 Oracle 10g 中为一个数据字典创建一个查询,该字典为给定模式中的所有表提取以下信息:
- 表名
- 列名
- 如果列是主键,则为“P”
- 如果此列在外键中引用,则表名 + '.' + 此外键指向的另一个表中主键的列名。
- 列数据类型
现在我只是想让它适用于给定模式中的单个表。我有一个查询,可以正确提取除第 4 项之外的所有内容。对于第 4 项,我在每一行中返回该行指向的外键(主键表名称和其他表中的列),而不仅仅是具有外键。
我无权写入任何架构,因此无法创建工作表或使用存储过程。我已经为此工作了很长时间,我开始怀疑是否可以在单个查询中提取此信息。
SELECT DISTINCT
t.table_name,
c.column_name,
(SELECT con.constraint_type
FROM all_constraints con, all_cons_columns cols
WHERE con.constraint_name = cols.constraint_name
AND con.owner = cols.owner
AND t.table_name = cols.table_name
AND c.column_name = cols.column_name
AND con.constraint_type = 'P' -- AND status = 'enabled'
)
AS pk_constraint,
(SELECT (SELECT conc.table_name || '.' || conc.column_name
FROM all_cons_columns conc
WHERE conc.owner = con.owner
AND constraint_name = con.r_constraint_name)
fk_ref
FROM all_constraints con, all_cons_columns col
WHERE con.owner = col.owner
AND con.table_name = t.table_name
AND con.constraint_name = col.constraint_name
AND con.constraint_type = 'R')
AS fk_constraint,
c.data_type,
d.comments
FROM all_tables t, all_tab_columns c, all_col_comments d
WHERE t.table_name = c.table_name
AND t.owner = c.owner
AND t.table_name = d.table_name
AND t.owner = d.owner
AND t.owner = %MY_SCHEMA_NAME%
AND t.table_name = %MY_TABLE_NAME%
ORDER BY t.table_name, c.column_name;
这是应该返回的内容(示例数据 - 假设 CustomerAddress.State 包含引用表 State 的代码,该表包含具有主键 State.StateCode 的状态代码列表):
- CustomerAddress AddressID P NULL NUMBER
- CustomerAddress StreetAddress NULL NULL VARCHAR(2)
- CustomerAddress State NULL State.StateCode CHAR
这是我的查询实际返回的内容。您可以看到每行都重复了 State.StateCode。它应该只出现在最后一行。
- CustomerAddress AddressID P State.StateCode NUMBER
- CustomerAddress StreetAddress NULL State.StateCode VARCHAR(2)
- CustomerAddress State NULL State.StateCode CHAR
感谢您的阅读!