前几天碰到一个需求,要用在所有用户表中查出某个表中是否含有某个值(不是字段。。。。),琢磨了一个上午,听起来
需求有点变态,Oracle是非关系型数据库,在不考虑性能场景下唯一能做的就是全库遍历,假设字段为varchar类型。
废话不多说,直接上存储过程:
CREATE OR REPLACE procedure QUERY_KEY
(
keyword in varchar2
)
as
v_SQLStatement varchar2(300);
v_startRecord Number;
begin
FOR reInfo IN (select table_name from user_tables) LOOP
FOR colInfo IN (SELECT column_name, DATA_TYPE FROM all_tab_cols WHERE table_name=reInfo.table_name) LOOP
IF (colInfo.DATA_TYPE='VARCHAR2') THEN
v_SQLStatement := 'select count(*) from '|| reInfo.table_name || ' where ' || colInfo.column_name || '= ' ||keyword;
execute immediate v_SQLStatement into v_startRecord;
IF(v_startRecord > 0) THEN
insert into TMPTABLE values (reInfo.table_name);
commit;
END IF;
END IF;
END LOOP;
END LOOP;
END QUERY_KEY;