根据关键字查询oracle中所有表的记录

     由于业务需要,根据关键字,查询所有表中所有字段包含该关键字的记录数,方便系统维护中核查数据。直接上代码,同行指正。

CREATE OR REPLACE PROCEDURE PM_QUERY_KEY_WORD_INFO (
  V_KEY_WORD IN VARCHAR2 
) AS 
  -- SQL STRING
  V_SQL     VARCHAR2(4000);
  -- FIELD OF TABLE
  V_TB_COL  VARCHAR2(512);
  -- RECORD NUMBER
  V_CNT     NUMBER(18,0);
  
  CURSOR CUR_SQLS IS 
    SELECT 'SELECT ''' || X.TABLE_NAME || '.' || X.COLUMN_NAME || ''' AS COL_NAME, NVL(COUNT(' || X.COLUMN_NAME || '),0) AS CNT FROM ' || X.TABLE_NAME 
           || ' A WHERE A.' || X.COLUMN_NAME || ' LIKE ''%' || V_KEY_WORD || '%''' AS SQL_STR 
    FROM COLS X JOIN USER_OBJECTS Y ON X.TABLE_NAME = Y.OBJECT_NAME
    WHERE Y.TEMPORARY <> 'Y' AND OBJECT_TYPE = 'TABLE' 
          AND X.DATA_TYPE IN ('CHAR','VARCHAR2','VARCHAR') 
    ORDER BY X.TABLE_NAME,COLUMN_ID;
/**
  维护使用:传入关键字,查询所有表,返回表对应字段含有关键字的记录数。遇到已经删除的表跳过。
*/
BEGIN
  FOR CV_SQL IN CUR_SQLS LOOP
    V_SQL := CV_SQL.SQL_STR; -- 获取将要执行的SQL语句;
    BEGIN
      EXECUTE IMMEDIATE V_SQL INTO V_TB_COL, V_CNT;
      IF V_CNT > 0 THEN
        DBMS_OUTPUT.PUT_LINE('表:' || SUBSTR(V_TB_COL,1,INSTR(V_TB_COL,'.',1,1) - 1) || ' 列:' || SUBSTR(V_TB_COL,INSTR(V_TB_COL,'.',1,1) + 1) ||
                             ' 有 ' || TO_CHAR(V_CNT)|| ' 条记录含有字串"' || V_KEY_WORD || '" ');
      END IF;
    EXCEPTION WHEN OTHERS THEN
      DBMS_OUTPUT.PUT_LINE('=== 错误语句:===' || V_SQL);
    END;
  END LOOP;
END PM_QUERY_KEY_WORD_INFO;


你可能感兴趣的:(数据库,大数据处理,oracle,关键字,数据记录查询,元数据)