1

我正在尝试在数据库中的每个视图中搜索诸如“%THIS%”之类的特定值

我想出了这个plsql代码

DECLARE
  match_count INTEGER;
BEGIN
  FOR t IN (SELECT name FROM user_dependencies where type = 'VIEW') LOOP

    EXECUTE IMMEDIATE 
    'SELECT COUNT(*) FROM '|| t.name || ' Where Column_Name LIKE ''%THIS%'' '
    INTO match_count;

    IF match_count > 0 THEN
      dbms_output.put_line( t.name ||' '||match_count );
    END IF;

  END LOOP;
END;

但是当我尝试运行它时,我在执行即时查询中收到列名的无效标识符错误。

对我来说问题很明显,不是每个视图都有 Column_Name,但我不知道如何在运行查询之前检查列是否存在,因为我循环遍历所有视图。

我还可以使用稍微修改过的版本来遍历所有表,虽然它们并不都有那一列,但我没有遇到这个问题。

编辑:我包括了可以用来循环遍历表的 plsql 代码。

DECLARE
  match_count INTEGER;
BEGIN
  FOR t IN (SELECT table_name, column_name FROM all_tab_columns 
            where table_name LIKE 'THIS%' and data_type = 'VARCHAR2' AND column_name = 'Column_name') LOOP

    EXECUTE IMMEDIATE 
    'SELECT COUNT(*) FROM '||t.table_name || ' Where Column_name LIKE ''%THIS%'' '
    INTO match_count;

    IF match_count > 0 THEN
      dbms_output.put_line( t.table_name ||' '||t.column_name||' '||match_count );
    END IF;

  END LOOP;
END;
4

2 回答 2

4

我假设这是 Oracle,因为您标记了 pl/sql。您可以使用 Oracle 的元数据表来查看表/视图具有哪些列。特别是 USER_TAB_COLUMNS

select count(*) 
from user_tab_columns 
where table_name = [name of view] 
and column_name = [name of column]
于 2012-11-02T17:57:42.523 回答
0

This should query every view that has a column_name like '%START%'

declare
cursor getViews is
select table_name, column_name from user_tab_cols where table_name in
(select view_name from user_views)
and column_name like '%START%';
myResult number;
BEGIN
   for i in getViews
   LOOP
      execute immediate 'select count(*) from '||i.table_name into myResult;
   END LOOP;
END;   
于 2012-11-02T19:11:16.270 回答