搜索所有列,所有表中的特定值

时间:2016-06-23 15:16:01

标签: sql oracle plsql

我知道这是一个重复的问题,但我无法找到重新开始讨论的方法。我试图创建一个存储过程,将搜索所有表中的所有列的值。这是我到目前为止创建的:

CLEAR SCREEN
SET VERIFY OFF
ACCEPT val CHAR PROMPT 'What value do you want to search for: '
CLEAR SCREEN;
DECLARE
 match_count integer;
 v_search_string varchar2(4000) := <<val>>;
 BEGIN  
 FOR t IN (SELECT owner,
 table_name, 
 column_name 
 FROM all_tab_columns
 WHERE data_type in ('CHAR', 'VARCHAR2', 'NCHAR', 'NVARCHAR2', 
 'CLOB', 'NCLOB') ) 
 LOOP   
   BEGIN
     EXECUTE IMMEDIATE    
       'SELECT COUNT(*) FROM '||t.owner || '.' || t.table_name||
       ' WHERE '||t.column_name||' = :1'   
       INTO match_count  
       USING v_search_string; 
     IF match_count > 0 THEN 
        dbms_output.put_line( t.owner || '.' || t.table_name ||' '||t.column_name||' '||match_count );
     END IF; 

    EXCEPTION
      WHEN others THEN
        dbms_output.put_line( 'Error encountered trying to read ' ||
            t.column_name || ' from ' || 
            t.owner || '.' || t.table_name );
     END;
 END LOOP;
END;
/

但我收到错误。任何帮助将非常感谢!!

1 个答案:

答案 0 :(得分:1)

见评论:

CLEAR SCREEN
SET VERIFY OFF
ACCEPT val CHAR PROMPT 'What value do you want to search for: '
CLEAR SCREEN;

DECLARE
    match_count                             INTEGER;
    v_search_string                         VARCHAR2(4000) := '&val'; /* this was <<val>> */
BEGIN
    FOR t IN (SELECT owner,
                     table_name,
                     column_name
                FROM all_tab_columns
               WHERE data_type IN ('CHAR',
                                   'VARCHAR2',
                                   'NCHAR',
                                   'NVARCHAR2',
                                   'CLOB',
                                   'NCLOB')) 
    LOOP
        BEGIN
            EXECUTE IMMEDIATE 'SELECT COUNT(*) FROM ' || t.owner || '.' || t.table_name || ' WHERE ' || t.column_name || ' = :1' INTO match_count USING v_search_string;

            IF match_count > 0
            THEN
                DBMS_OUTPUT.put_line(t.owner || '.' || t.table_name || '     ' || t.column_name || ' ' || match_count);
            END IF;
        EXCEPTION
            WHEN OTHERS
            THEN
                DBMS_OUTPUT.put_line('Error encountered trying to read ' || t.column_name || ' from ' || t.owner || '.' || t.table_name);
        END;
    END LOOP; 
END;
/