![](/img/trans.png)
[英]How to select data from multiple tables where table name is value from a column of another table?
[英]select table name from all tables where column has specific value
我需要 select 列具有特定值的所有表中的表名,例如:
select table_name from all_tab_columns where column_name = 'VALUE';
但有价值的条件谢谢
您想要的是搜索数据库中的所有列,其中一些值说“ABC”和此类表的列表。
为此,您必须编写一个动态脚本来在一个表中选择一个表并搜索该表中的所有列并循环遍历它。
好吧,不清楚您要的是什么,是表的列名还是列本身的实际值。
我想这是第二个,因为你已经知道第一个。 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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.