Vivek Gupta
Vivek Gupta

Reputation: 2814

PL / SQL to search a string in whole database

More than a question, its an information sharing post.

I have come across a situation today where i needed to look for a sting in the entire database of an application with no idea of, which table/column it belongs to.

Below is a PL/SQL block i wrote and used to help my propose. Hope its helps others to with a similar requirement.

Declare
  i   NUMBER := 0;
  counter_intable NUMBER :=0;
 BEGIN
     FOR rec IN (
        select 
             'select count(*) ' || 
             ' from '||table_name||
             ' where '||column_name||' like''%732-851%'' ' as sql_command
        from user_tab_columns
        where data_type='VARCHAR2'
     )
     LOOP
        execute immediate rec.sql_command into counter_intable;
        IF counter_intable != 0 THEN
            i := i + 1;
            DBMS_OUTPUT.put_line ('Match found using command ::' || rec.sql_command);
            DBMS_OUTPUT.put_line ('count ::' || counter_intable);
        END IF;

     END LOOP;

     DBMS_OUTPUT.put_line ('total commands matched :: ' || i);
 END;

replace your string at the place of : 732-851 in the code block

Upvotes: 2

Views: 3389

Answers (1)

Lalit Kumar B
Lalit Kumar B

Reputation: 49112

Why PL/SQL? You could do the same in SQL using xmlsequence.

For example, I want to search for the value 'KING' -

SQL> variable val varchar2(10)
SQL> exec :val := 'KING'

PL/SQL procedure successfully completed.

SQL> SELECT DISTINCT SUBSTR (:val, 1, 11) "Searchword",
  2    SUBSTR (table_name, 1, 14) "Table",
  3    SUBSTR (column_name, 1, 14) "Column"
  4  FROM cols,
  5    TABLE (xmlsequence (dbms_xmlgen.getxmltype ('select '
  6    || column_name
  7    || ' from '
  8    || table_name
  9    || ' where upper('
 10    || column_name
 11    || ') like upper(''%'
 12    || :val
 13    || '%'')' ).extract ('ROWSET/ROW/*') ) ) t
 14  ORDER BY "Table"
 15  /

Searchword  Table          Column
----------- -------------- --------------
KING        EMP            ENAME

SQL>

You could search for any data type values, please read SQL to Search for a VALUE in all COLUMNS of all TABLES in an entire SCHEMA

Upvotes: 1

Related Questions