从ORACLE数据库中查询特定的数据

如果你想从oracle数据库中查询一个特定值所在的表的名称和字段名称,而数据库中表的数量很多无法手动一个一个来查看,这时编写plsql让数据库自己查询就显得非常必要了。

在这里我编写了一个plsql来查询数据库中值为“57d486c2:1385142d983:”的数据表名称和字段名称。

--查询oracle数据库中该用户表中字段值为str的表名称和字段名称
declare 
str varchar2(100) := '57d486c2:1385142d983:';
sqlstr varchar2(4000);
tablename varchar2(50);
columnname varchar2(50);
cursor selectSqlCur is select table_name,column_name from user_tab_cols where data_type='VARCHAR2';
begin
  open selectSqlCur;
  fetch selectSqlCur into tablename, columnname;
  while selectSqlCur%found loop
    sqlstr := 'declare '||
      'scount number(10); '||
      'begin select count(*) into scount from '||tablename||' where '||columnname||'='''||str||'''; '||
      'if scount != 0 then '||
      'dbms_output.put_line('''||tablename||'.'||columnname||'''); '||
      'end if; '||
      'end;';
      --打印sql语句
      --dbms_output.put_line(sqlstr);
      --执行sql语句
      execute immediate sqlstr;
    fetch selectSqlCur into tablename, columnname;
  end loop;
end;

猜你喜欢

转载自wangmuchang.iteye.com/blog/1731636