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

前端之家收集整理的这篇文章主要介绍了根据关键字查询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) || ' 列:' || SUBSTR(V_TB_COL,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;
原文链接:https://www.f2er.com/oracle/212560.html

猜你在找的Oracle相关文章