Search All Fields In All Tables For A Specific Value (Oracle)

前端 未结 16 2077
一整个雨季
一整个雨季 2020-11-22 01:05

Is it possible to search every field of every table for a particular value in Oracle?

There are hundreds of tables with thousands of rows in some tables so I know th

16条回答
  •  情话喂你
    2020-11-22 01:43

    Procedure to Search Entire Database:

        CREATE or REPLACE PROCEDURE SEARCH_DB(SEARCH_STR IN VARCHAR2, TAB_COL_RECS OUT VARCHAR2) IS
          match_count integer;
          qry_str varchar2(1000);
          CURSOR TAB_COL_CURSOR IS 
              SELECT TABLE_NAME,COLUMN_NAME,OWNER,DATA_TYPE FROM ALL_TAB_COLUMNS WHERE DATA_TYPE in ('NUMBER','VARCHAR2') AND OWNER='SCOTT';
              BEGIN  
                FOR TAB_COL_REC  IN TAB_COL_CURSOR
                LOOP
                  qry_str := 'SELECT COUNT(*) FROM '||TAB_COL_REC.OWNER||'.'||TAB_COL_REC.TABLE_NAME|| 
                  ' WHERE '||TAB_COL_REC.COLUMN_NAME;
                   IF TAB_COL_REC.DATA_TYPE = 'NUMBER' THEN
                          qry_str := qry_str||'='||SEARCH_STR; 
                   ELSE
                           qry_str := qry_str||' like '||SEARCH_STR; 
                   END IF;
                           --dbms_output.put_line( qry_str );
                    EXECUTE IMMEDIATE  qry_str  INTO match_count;
                    IF match_count > 0 THEN          
                       dbms_output.put_line( qry_str );
                      --dbms_output.put_line( TAB_COL_REC.TABLE_NAME ||' '||TAB_COL_REC.COLUMN_NAME ||' '||match_count);     
                        TAB_COL_RECS := TAB_COL_RECS||'@@'||TAB_COL_REC.TABLE_NAME||'##'||TAB_COL_REC.COLUMN_NAME;
                    END IF; 
              END LOOP;
         END SEARCH_DB;    
    

    Execute Statement

      DECLARE
        SEARCH_STR VARCHAR2(200);
        TAB_COL_RECS VARCHAR2(200);
        BEGIN
          SEARCH_STR := 10;
          SEARCH_DB(
            SEARCH_STR => SEARCH_STR,
            TAB_COL_RECS => TAB_COL_RECS
          );
         DBMS_OUTPUT.PUT_LINE('TAB_COL_RECS = ' || TAB_COL_RECS);
         END;
    

    Sample Results

    Connecting to the database test.
    SELECT COUNT(*) FROM SCOTT.EMP WHERE DEPTNO=10
    SELECT COUNT(*) FROM SCOTT.DEPT WHERE DEPTNO=10
    TAB_COL_RECS = @@EMP##DEPTNO@@DEPT##DEPTNO
    Process exited.
    Disconnecting from the database test.
    

提交回复
热议问题