在搜索值之前检查视图中是否存在列

时间:2012-11-02 17:48:38

标签: sql view plsql

我正在尝试搜索数据库中的每个视图,以获取类似“%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;

但是当我尝试运行它时,我在execute immeadiate查询中得到了列名无效的标识符错误。

问题很明显,并非每个视图都有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;

2 个答案:

答案 0 :(得分: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]

答案 1 :(得分:0)

这应该查询每个具有column_name的视图,例如'%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;