初衷是想根据表中存在的外键信息得到相应的索引脚本,后来才扩展到获取相应的主键字段,大同小异。
这些系统表都是相类似的,例如user_cons_columns 和user_constraints, user_indexes和user_ind_columns
定义一个函数,把多列的约束字段以逗号串起来
create or replace function f_GetConstraintColumn(itablename in Varchar2,iConstraintName in Varchar2)
return varchar2 is
type cur_type is ref cursor;
myCur cur_type;
v_Column1Value varchar2(4000);
v_Result varchar2(32767);
begin
Open myCur for Select COLUMN_NAME
From user_cons_columns
Where table_name=itablename And constraint_name=iConstraintName
Order By POSITION;
Loop
Fetch myCur Into v_Column1Value;
Exit When myCur%notfound;
v_Result:=v_Result||v_Column1Value||',';
End Loop;
Close myCur;
v_Result:=substr(v_Result,1,length(v_Result)-1);
return(v_Result);
end ;
return varchar2 is
type cur_type is ref cursor;
myCur cur_type;
v_Column1Value varchar2(4000);
v_Result varchar2(32767);
begin
Open myCur for Select COLUMN_NAME
From user_cons_columns
Where table_name=itablename And constraint_name=iConstraintName
Order By POSITION;
Loop
Fetch myCur Into v_Column1Value;
Exit When myCur%notfound;
v_Result:=v_Result||v_Column1Value||',';
End Loop;
Close myCur;
v_Result:=substr(v_Result,1,length(v_Result)-1);
return(v_Result);
end ;
--该语句用来得到外键表、外键约束名称、外键字段和相应的主键表、主键字段,主键约束名称等等,稍作改动便可以写出创建相应的约束脚本和索引脚本
Select
a.table_name ForeignKeyTableName, a.constraint_name,f_GetConstraintColumn(a.table_name, a.constraint_name) ForeignKeyColumnsName,
a.r_constraint_name,b.table_name PrimaryKeyTableName,f_GetConstraintColumn(b.table_name, a.r_constraint_name) PrimaryKeyColumnsName
From user_constraints a,user_constraints b
Where a.constraint_type='R'
And a.r_constraint_name=b.constraint_name
-- And a.table_name = 'T_FACTORING_INV'
Order By a.table_name, a.constraint_name
a.table_name ForeignKeyTableName, a.constraint_name,f_GetConstraintColumn(a.table_name, a.constraint_name) ForeignKeyColumnsName,
a.r_constraint_name,b.table_name PrimaryKeyTableName,f_GetConstraintColumn(b.table_name, a.r_constraint_name) PrimaryKeyColumnsName
From user_constraints a,user_constraints b
Where a.constraint_type='R'
And a.r_constraint_name=b.constraint_name
-- And a.table_name = 'T_FACTORING_INV'
Order By a.table_name, a.constraint_name
本文转自baoqiangwang51CTO博客,原文链接:http://blog.51cto.com/baoqiangwang/312778
,如需转载请自行联系原作者