从列具有特定值的所有表中选择表名称

时间:2020-08-20 13:16:27

标签: sql oracle

我需要从列具有特定值的所有表中选择表名 像这样:

select table_name from all_tab_columns where column_name = 'VALUE';

但有条件的条件 谢谢

2 个答案:

答案 0 :(得分:0)

您想要的是搜索数据库中所有带有“ ABC”值和此类表列表的列。

为此,您必须编写一个动态脚本以在一个表中选择一个表并搜索该表中的所有列并遍历该表。

答案 1 :(得分:0)

好吧,不清楚您要的是表的列名还是列本身的实际值。

我想这是第二个,作为您已经知道的第一个。 Oracle不会在任何字典视图中存储列值,因为这是没有意义的。值存储在相应的表中。

因此,一种方法可以使用PL / SQL,但是如果您的数据库很大,则将花费很长时间。在我的示例中,我正在寻找一个只能通过应用于数据类型为varchar2或char的列来限制的字符串,并且当我在寻找特定值时,我丢弃了所有长度小于该值的列我在找。

set serveroutput on size unlimited echo on verify off timing on 
declare
vowner varchar2(128);
vtable varchar2(128);
vcolum varchar2(128);
vvalue varchar2(40) := 'TEST_TABLE';
vcount pls_integer;
begin
for c in ( select owner , table_name from all_tables order by 1 , 2 )
loop 
    vowner := c.owner;
    vtable := c.table_name ;
    for h in ( select column_name from all_tab_columns where owner = vowner and table_name = vtable 
               and data_type in ( 'CHAR' ,  'VARCHAR2' ) and data_length >= length(vvalue) 
               order by column_id )
    loop
        vcolum := h.column_name;
        execute immediate ' select count(*) from '||vowner||'.'||vtable||' where upper('||vcolum||') = '''||vvalue||''' ' into vcount ;
        if vcount > 0
        then 
            dbms_output.put_line('Found '||vvalue||' in table --> '||vowner||'.'||vtable||' | column --> '||vcolum||' ');
        end if;
    end loop;
end loop;
end;
/

我限制表​​格查找的示例

SQL> set serveroutput on size unlimited echo on verify off timing on lines 200
declare
vowner varchar2(128);
vtable varchar2(128);
vcolum varchar2(128);
vvalue varchar2(40) := 'TEST_TABLE';
vcount pls_integer;
begin
for c in ( select owner , table_name from all_tables where owner = 'TEST_PERF' order by 1 , 2 )
loop
        vowner := c.owner;
        vtable := c.table_name ;
        for h in ( select column_name from all_tab_columns where owner = vowner and table_name = vtable and data_type in ( 'CHAR' ,  'VARCHAR2' ) and data_length >= length(vvalue)  order by column_id )
        loop
                vcolum := h.column_name;
                execute immediate ' select count(*) from '||vowner||'.'||vtable||' where upper('||vcolum||') = '''||vvalue||''' ' into vcount ;
                if vcount > 0
                then
                      dbms_output.put_line('Found '||vvalue||' in table --> '||vowner||'.'||vtable||' | column --> '||vcolum||' ');
                end if;
      end loop;
end loop;
end;
/

Found TEST_TABLE in table --> TEST_PERF.T | column --> C1
Found TEST_TABLE in table --> TEST_PERF.TEST_OBJECTS | column --> OBJECT_NAME

PL/SQL procedure successfully completed.

Elapsed: 00:00:17.29
SQL>
相关问题