我希望oracle中的查询通过传递值来从表中获取列名。 意味着在大多数情况下 - 我们写这样的查询 - select * from table where column ='value'。但在我的情况下我不知道列名。
任何人都可以建议我。 提前谢谢......
答案 0 :(得分:0)
您可以尝试构建动态查询来检查数据库的所有表。
<强>设置:强>
create table tab1 ( v1 varchar2(100), n1 number, v1b varchar2(100));
create table tab2 ( v2 varchar2(100), n2 number, v2b varchar2(100));
create table tab3 ( v3 varchar2(100), n3 number, v3b varchar2(100));
insert into tab1 values ('Maria', 1, 'aa');
insert into tab1 values ('xx', 2, 'bb');
insert into tab2 values ('yy', 3, 'Maria');
insert into tab2 values ('zz', 3, 'cc');
insert into tab3 values ('WW', 4, 'DD');
构建动态查询:
select 'select table_name,
matches from (' || listagg(statement, ' UNION ALL ') within group (order by table_name) || ')
where matches > 0'
from (
select 'select ''' || table_name ||
''' as TABLE_NAME, count(1) as MATCHES from ' || table_name || ' WHERE ' ||
listagg(column_name || ' = ''Maria''', ' OR ') within group (order by column_name) as statement,
table_name
from user_tab_columns col
where data_type = 'VARCHAR2'
group by table_name
)
这将返回一个查询,您可以运行该查询来检查所有表;在我的例子中,这将构建查询(未格式化):
SELECT table_name, matches
FROM (SELECT 'TAB1' AS TABLE_NAME, COUNT(1) AS MATCHES
FROM TAB1
WHERE V1 = 'Maria'
OR V1B = 'Maria'
UNION ALL
SELECT 'TAB2' AS TABLE_NAME, COUNT(1) AS MATCHES
FROM TAB2
WHERE V2 = 'Maria'
OR V2B = 'Maria'
UNION ALL
SELECT 'TAB3' AS TABLE_NAME, COUNT(1) AS MATCHES
FROM TAB3
WHERE V3 = 'Maria'
OR V3B = 'Maria')
WHERE matches > 0;
运行此查询将给出:
TABL MATCHES
---- ----------
TAB1 1
TAB2 1
请注意我使用了USER_TAB_COLUMNS
,因此只搜索登录模式的表格;如果要搜索不同的模式,可以使用ALL_TAB_COLUMNS
或DBA_TAB_COLUMNS
,具体取决于您的需要和用户的权限;有关更多信息,请参阅here。
另外,请考虑USER_TAB_COLUMNS
将获取表和视图的列;如果您想限制搜索到表格,可以将USER_TAB_COLUMNS
(ALL_TAB_COLUMNS
,DBA_TAB_COLUMNS
)加入USER_TABLES
(ALL_TABLES
,DBA_TABLES
) TABLE_NAME
或TABLE_NAME
和OWNER
如果您决定使用ALL或DBA表:
SQL> create view vTab1 as select * from tab1;
View created.
SQL> select count(1)
2 from user_tab_columns
3 where table_name = 'VTAB1';
COUNT(1)
----------
3
SQL> select count(1)
2 from user_tab_columns
3 inner join user_tables using(table_name)
4 where table_name = 'VTAB1';
COUNT(1)
----------
0
SQL>
答案 1 :(得分:-2)
select table_name from user_Tables where table_name = 'bogus';