This is not a normal part of the database functionality. However, you are not the first person to ask for this, or anything like that.
The solution requires two things. The first is a data dictionary; the Oracle database does not support Reflection, but it does have a set of views that give us metadata about our database objects. In this case, we need user_tab_columns , which will give us the columns for this table. Secondly, it is dynamic SQL; this is the ability to collect an SQL query at runtime and then execute it. There are several ways to do this, but ref cursors are commonly used.
The following code is a proof of concept. It takes four parameters:
- name of the table you want to find
- primary key name of this table Column
- primary key value that you want to restrict
- the value you want to find.
This is no longer the case, so you may need to edit it to tidy up the result or make the program more flexible.
create or replace procedure search_cols (tname in user_tables.table_name%type , pk_col in user_tab_columns.column_name%type , pk in number , val in number ) is firstcol boolean := true; stmt varchar2(32767); result varchar2(32767); rc sys_refcursor; begin stmt := 'select '; << projection >> for lrec in ( select column_name from user_tab_columns where table_name = tname and column_name != pk_col and data_type = 'NUMBER' order by column_id ) loop if not firstcol then stmt := stmt || chr(10) || '||'',''||'; else firstcol := false; end if; stmt := stmt || ' case when '|| lrec.column_name||' = '|| val || ' then '''|| lrec.column_name || ''' else null end'; end loop projection; stmt := stmt || chr(10)|| ' from '||tname||' where '|| pk_col || ' = '|| pk; -- dbms_output.put_line(stmt); open rc for stmt; fetch rc into result; close rc; dbms_output.put_line(tname || '::' || val || ' found in '||result); end search_cols; /
As you can see, dynamic SQL is hard to read. Itβs harder to debug :) So it's nice to have the means to show the final statement.
Anyway, here are the results:
SQL> set serveroutput on size unlimited SQL> exec search_cols('T23', 'ID', 111, 10) T23::10 found in ,COL_B,COL_C, PL/SQL procedure successfully completed. SQL> exec search_cols('T23', 'ID', 222, 10) T23::10 found in COL_A,,, PL/SQL procedure successfully completed. SQL>