gpt4 book ai didi

Oracle 在所有表的所有列中搜索字符串

转载 作者:行者123 更新时间:2023-12-03 01:17:09 24 4
gpt4 key购买 nike

我需要在 Oracle 数据库中搜索所有表和列中的字符串。我在网上找到了以下查询,但是当我执行它时,出现以下错误

感谢任何帮助

ORA-06550: line 6, column 31:
PL/SQL: ORA-00904: "COLUMN_NAME": invalid identifier
ORA-06550: line 6, column 12:
PL/SQL: SQL Statement ignored
ORA-06550: line 8, column 30:
PLS-00364: loop index variable 'T' use is invalid
ORA-06550: line 7, column 4:
PL/SQL: Statement ignored
ORA-06550: line 12, column 38:
PLS-00364: loop index variable 'T' use is invalid
ORA-06550: line 12, column 16:
PL/SQL: Statement ignored

BEGIN
FOR t IN (SELECT table_name, column_name FROM all_tables) LOOP
EXECUTE IMMEDIATE
'SELECT COUNT(*) FROM '||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.table_name ||' '||t.column_name||' '||match_count );
END IF;
END LOOP;
END;
/

最佳答案

至少,您需要查询 ALL_TAB_COLUMNS,而不是 ALL_TABLES

DECLARE
match_count integer;
v_search_string varchar2(4000) := <<string you want to search for>>;
BEGIN
FOR t IN (SELECT owner, table_name, column_name FROM all_tab_columns) LOOP
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;
END LOOP;
END;
/

但是,如果您正在查找字符串,那么您几乎肯定会希望将自己限制为查找可以存储字符串的列。例如,在 DATE 列中搜索字符串是没有意义的。除非您对 BLOB 列包含的内容有大量先验知识,并且能够解析 BLOB 列的二进制格式,否则在 BLOB 列中搜索字符串是没有意义的。鉴于此,我怀疑您想要更像的东西

DECLARE
match_count integer;
v_search_string varchar2(4000) := <<string you want to search for>>;
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;
/

当然,这会非常慢——对于表中的每个字符串列,您都需要对每个表进行一次全面扫描。对于中等大小的表和中等数量的字符串列,这可能需要相当长的时间。

关于Oracle 在所有表的所有列中搜索字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6389666/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com