您可以创建一个函数来组合数据字典查询以查找父子关系并DBMS_XMLGEN.GETXML
生成和组合 XML。
下面的函数采用 a ROWID
,查找父表和子表,并为相关行生成 XML。这里有很多假设,这可能需要大量的工作才能处理真实数据。
create or replace function get_related_xml(p_rowid rowid) return xmltype is
v_child_table_owner varchar2(128);
v_child_table_name varchar2(128);
v_parent_table_owner varchar2(128);
v_parent_table_name varchar2(128);
v_column varchar2(128);
v_child_xml xmltype;
v_parent_xml xmltype;
v_combined_xml xmltype;
begin
--Get child table directly referenced by ROWID.
select owner, object_name
into v_child_table_owner, v_child_table_name
from all_objects
where object_type = 'TABLE'
and object_id = dbms_rowid.rowid_object(p_rowid);
--Get parent table based on child table ROWID, and join columns.
--(ASSUMPTION: Tables only have one column, with the same name, that joins the tables.)
select owner, table_name, column_name
into v_parent_table_owner, v_parent_table_name, v_column
from all_cons_columns
where (owner, constraint_name) in
(
--Foreign key constraints based on the relevant table.
select r_owner, r_constraint_name
from all_constraints
where constraint_type = 'R'
and (owner, table_name) in
(
--Table referenced by ROWID.
select owner, object_name
from all_objects
where object_type = 'TABLE'
and object_id = dbms_rowid.rowid_object(p_rowid)
)
);
--Generate child XML.
v_child_xml := dbms_xmlgen.getXMLType
(
'select c.*
from '||v_child_table_owner||'.'||v_child_table_name||' c
join '||v_parent_table_owner||'.'||v_parent_table_name||' p
on c.'||v_column||' = p.'||v_column||'
where c.rowid = '''||p_rowid||''''
);
--Generate parent XML.
v_parent_xml := dbms_xmlgen.getXMLType
(
'select p.*
from '||v_child_table_owner||'.'||v_child_table_name||' c
join '||v_parent_table_owner||'.'||v_parent_table_name||' p
on c.'||v_column||' = p.'||v_column||'
where c.rowid = '''||p_rowid||''''
);
--Combine the XML and return them.
select xmlconcat(v_child_xml, v_parent_xml)
into v_combined_xml
from dual;
return v_combined_xml;
end get_related_xml;
/
调用函数很容易。当前版本不会以您想要的格式返回数据,您可能需要转换 XML。
select get_related_xml(rowid)
from table1
where rollno=15;
<ROWSET>
<ROW>
<ID>2</ID>
<NAME>bbb</NAME>
<ROLLNO>15</ROLLNO>
</ROW>
</ROWSET>
<ROWSET>
<ROW>
<ID>2</ID>
<ROLLNO>15</ROLLNO>
<DIV>b</DIV>
</ROW>
</ROWSET>
这是我用来生成上述结果的示例模式。这是一个简单的模式,只有一个父子关系,基于两个表中具有相同名称的单个列。
create table table2(id number primary key, rollNo number unique, div varchar2(100));
insert into table2
select 1, 10, 'a' from dual union all
select 2, 15, 'b' from dual;
create table table1(id number primary key, name varchar2(100), rollNo number,
constraint table1_fk foreign key (rollNo) references table2(rollNo));
insert into table1
select 1, 'aaa', 10 from dual union all
select 2, 'bbb', 15 from dual;