Oracle生成查询包含指定字段名对应的所有数据表记录语句

时间:2022-02-03 08:15:27

应用场合:已知字段名字,查询数据库中所有数据表中包含该字段名的所有数据表

操作办法:指定字段名,数据库表用户,执行下面查询语句即可

--Oracle生成查询包含指定字段名对应的所有数据表记录语句

declare

mycolumnname VARCHAR(255):='userid';--定义要查询的字段名变量,运行前修改成您要查询的字段名
myownername VARCHAR(255):='system';--定义要查询的数据库用户名变量,运行前修改成您要查询的数据库用户名
mystring NVARCHAR2(4000):=''; --定义要输出的字符串变量   

cursor mycursor is --定义游标          
select * from dba_tab_columns where lower(column_name)=mycolumnname and lower(owner)=myownername;
myrecord mycursor%rowtype;  --定义游标记录类型   
Counter int :=0;   
begin   
open mycursor;  --打开游标   
if mycursor%isopen  then  --判断打开成功   
loop --循环获取记录集     
fetch mycursor into myrecord; --获取游标中的记录         

if mycursor%found then  --游标的found属性判断是否有记录  

mystring:='select * from '||myrecord.table_name||';';
dbms_output.put_line(mystring);    

else            
exit;
end if;
   
end loop;   
else     
dbms_output.put_line('游标没有打开');   
end if;  
close mycursor;

end;


运行结果类似于下面的语句:
select * from DEF$_PROPAGATOR;
select * from REPCAT$_REPCATLOG;
select * from REPCAT$_REPGROUP_PRIVS;
select * from SQLPLUS_PRODUCT_PROFILE;
select * from PRODUCT_PRIVS;