Retrieval of Column name in Oracle - sql

how to retrieve a column name based on the value given in i wnat to get the column_name in oracle
like i dont know a cloumn name but i know the column value
i have tried in this way
select column_name from table_name where column_value=XXXXX;

Try like this:
SQL> select table_name,
column_name,
:search_string search_string,
result
from cols,
xmltable(('ora:view("'||table_name||'")/ROW/'||column_name||'[ora:contains(text(),"%'|| :search_string || '%") > 0]')
columns result varchar2(10) path '.'
)
where table_name in ('EMP', 'DEPT')
Source

If you want to do it in plain SQL, then you could use the XML approach.
For example, to search for the value KING in SCOTT schema:
SQL> variable val varchar2(10)
SQL> exec :val := 'KING'
PL/SQL procedure successfully completed.
SQL> SELECT DISTINCT SUBSTR (:val, 1, 11) "Searchword",
2 SUBSTR (table_name, 1, 14) "Table",
3 SUBSTR (column_name, 1, 14) "Column"
4 FROM cols,
5 TABLE (xmlsequence (dbms_xmlgen.getxmltype ('select '
6 || column_name
7 || ' from '
8 || table_name
9 || ' where upper('
10 || column_name
11 || ') like upper(''%'
12 || :val
13 || '%'')' ).extract ('ROWSET/ROW/*') ) ) t
14 ORDER BY "Table"
15 /
Searchword Table Column
----------- -------------- --------------
KING EMP ENAME
SQL>
Read SQL to Search for a VALUE in all COLUMNS of all TABLES in an entire SCHEMA

Related

How can I Create a generic procedure for inserting data from a table?

I have a table:
create table D_DEFAULT
(
table_name VARCHAR2(200),
column_name VARCHAR2(200),
column_value VARCHAR2(200)
);
TABLE_NAME
COLUMN_NAME
COLUMN_VALUE
GCG_RTM
ID
-1
GCG_RTM
FILIAL_CODE
US
GCG_RTM
SK_ID
-1
GCG_RTM
SUBS_ID
-1
In my project i have to take data from columns COLUMN_NAME and COLUMN_VALUE
and insert it into another table.
Something like this:
select LISTAGG(COLUMN_NAME, ','), LISTAGG(COLUMN_VALUE, ',')
into v_columns, v_values
from D_DEFAULT
where TABLE_NAME = p_table || '_RTM';
v_sql := 'insert into table ' || p_table || ' values (' || v_values|| ') ';
It is dynamic SQL you need (as you more or less figured out yourself).
Sample data and table:
SQL> select * From d_default;
TABLE_NAME COLUMN_NAME COLUMN_VALUE
--------------- --------------- ---------------
GCG_RTM ID -1
GCG_RTM FILIAL_CODE US
SQL> desc gcg_rtm
Name Null? Type
----------------------------------------- -------- ----------------------------
ID NUMBER
FILIAL_CODE VARCHAR2(5)
Code:
SQL> declare
2 l_tab varchar2(30);
3 l_cols varchar2(200);
4 l_vals varchar2(200);
5 l_str varchar2(2000);
6 begin
7 select table_name,
8 listagg(column_name, ',') within group (order by rowid),
9 chr(39) || listagg(column_value, chr(39) ||','|| chr(39)) within group (order by rowid) ||chr(39)
10 into l_tab, l_cols, l_vals
11 from d_default
12 where table_name = 'GCG_RTM'
13 group by table_name;
14
15 l_str := 'insert into ' || l_tab || ' (' ||
16 l_cols ||') values (' || l_vals || ')';
17
18 execute immediate l_str;
19 end;
20 /
PL/SQL procedure successfully completed.
Result:
SQL> select * from gcg_rtm;
ID FILIA
---------- -----
-1 US
SQL>
Problems you can expect: different datatypes. It is easy to insert strings or numbers (and rely on Oracle's implicit datatype conversion), but - what about e.g. dates? How to apply TO_DATE function? Which format model will you use? Maybe your D_DEFAULT table lacks in some more info - at least datatype and format_model.

Simplifying a complex SQL query into a simple query

The below query generates a select statement. Instead of generating the select statement I want the query to execute the select statement that is getting generating and also display the TABLE_NAME, COLUMN_NAME, DATA_TYPE and the MAX(COLUMN_SIZE), and group the results by TABLE_NAME and sort the results in descending order based on the max size of the LOB column.
select table_name,
column_name,
data_type,
'select (max(length(' || COLUMN_NAME || '))/(1024)) as "Size in KB" from '
|| owner || '.' || TABLE_NAME ||';' "querytogetlobsize"
from dba_tab_cols
where owner='&SCHEMA'
and data_type in ('CLOB','BLOB','NCLOB');
Could anyone help me with generating the query. Thank you so much for your help in advance!
Dynamic SQL it is.
SQL> SET SERVEROUTPUT ON
SQL>
SQL> DECLARE
2 l_size NUMBER;
3 BEGIN
4 FOR cur_r
5 IN (SELECT table_name,
6 column_name,
7 data_type,
8 'select (max(length('
9 || COLUMN_NAME
10 || '))/(1024)) as "Size in KB" from '
11 || owner
12 || '.'
13 || TABLE_NAME querytogetlobsize
14 FROM all_tab_cols
15 WHERE owner = 'SCOTT'
16 AND data_type IN ('CLOB', 'BLOB', 'NCLOB'))
17 LOOP
18 EXECUTE IMMEDIATE cur_r.querytogetlobsize
19 INTO l_size;
20
21 DBMS_OUTPUT.put_line (
22 RPAD (cur_r.table_name, 20, ' ')
23 || ' - '
24 || RPAD (cur_r.column_name, 20, ' ')
25 || ': '
26 || TO_CHAR (l_size, '999G990D00'));
27 END LOOP;
28 END;
29 /
which results in
DUGOTRAJNO - KRAJ_BLOB : 1.708,98
DUGOTRAJNO - POCETAK_BLOB : 2.596,62
OSOBA - PHOTO : 390,32
OSOBA - FAKSIMIL : 23,18
ZAHTJEV_PUTNI_NA - NALOG_BLOB : 16.286,69
ZAHTJEV_PUTNI_NA - POZIV_BLOB : 25.609,50
PL/SQL procedure successfully completed.
SQL>

How to find column name that contains specific string value using oracle

How to find column name contains particular string value in my table sku_config using oracle.
for example my string is TRP , I need to find the column name that is having value 'TRP' in mytable.
here column name can be any column belongs to my table.
Here is psudo code for my requirement.
select column_name from sku_config where contains 'TRP'.
You can use xmlquery as follows:
SELECT column_name FROM
(select column_name,
to_number(xmlquery('/ROWSET/ROW/C/text()'
passing xmltype(dbms_xmlgen.getxml(
'select count(1) as c '
|| 'from ' || table_name || ' WHERE ' || column_name || ' LIKE ''%TRP%'''))
returning content)) as c
from all_tab_columns
where TABLE_NAME = 'SKU_CONFIG')
WHERE C > 0;
Example:
Current data of sample table:
SQL> SELECT * FROM ABC;
NAME DE
--------------- --
TEJASH2 SO
TEJASH3 DO
ABC SO
XXXXXXXXX SO
A A
B B
TEJASH1 SO
7 rows selected.
Searching for TEJASH string
SQL> SELECT column_name FROM
2 (select column_name,
3 to_number(xmlquery('/ROWSET/ROW/C/text()'
4 passing xmltype(dbms_xmlgen.getxml(
5 'select count(1) as c '
6 || 'from ' || table_name || ' WHERE ' || column_name || ' LIKE ''%TEJASH%'''))
7 returning content)) as c
8 from all_tab_columns
9 where TABLE_NAME = 'ABC')
10 WHERE C > 0;
COLUMN_NAME
-------------
NAME
Searching for SO string
SQL>
SQL>
SQL> SELECT column_name FROM
2 (select column_name,
3 to_number(xmlquery('/ROWSET/ROW/C/text()'
4 passing xmltype(dbms_xmlgen.getxml(
5 'select count(1) as c '
6 || 'from ' || table_name || ' WHERE ' || column_name || ' LIKE ''%SO%'''))
7 returning content)) as c
8 from all_tab_columns
9 where TABLE_NAME = 'ABC')
10 WHERE C > 0;
COLUMN_NAME
------------
DEPT
SQL>
If you want to find the names of the columns in a table that look like something, then use user_tab_columns:
select column_name
from user_tab_columns
where table_name = 'sku_config' and
column_name like '%TRP%';
you can use the following code to find a column with a specific string.
select COLUMN_NAME
from TABLE_NAME
where COLUMN_NAME="STRING"
group by COLUMN_NAME

query to find the value in all the tables of the database

I am searching for a specific value in the table and there are lot of tables, is there a query to find the value in all the tables of the database so that I can quickly find the value without going through each table one by one.
I have already tried
SELECT owner, table_name, column_name FROM all_tab_columns WHERE column_name LIKE '%52871%';
SELECT * from dba_objects WHERE object_name like '%52871%'
You could search for a VALUE in all COLUMNS of all TABLES in an entire SCHEMA using XML SQL:
For example, I want to search for value KING in all columns of all the tables in entire SCOTT schema:
SQL> variable val varchar2(10)
SQL> exec :val := 'KING'
PL/SQL procedure successfully completed.
SQL> SELECT DISTINCT SUBSTR (:val, 1, 11) "Searchword",
2 SUBSTR (table_name, 1, 14) "Table",
3 SUBSTR (column_name, 1, 14) "Column"
4 FROM cols,
5 TABLE (xmlsequence (dbms_xmlgen.getxmltype ('select '
6 || column_name
7 || ' from '
8 || table_name
9 || ' where upper('
10 || column_name
11 || ') like upper(''%'
12 || :val
13 || '%'')' ).extract ('ROWSET/ROW/*') ) ) t
14 ORDER BY "Table"
15 /
Searchword Table Column
----------- -------------- --------------
KING EMP ENAME

Selecting all rows where a set of column values is not null

I have a complex table in Oracle which is intentionally not normalized. It has a huge number of columns with observations in each col
something like
Table1
ID,obs1,obs2,obs2,obs3... obs100
Is there a way to select ALL rows where all obs columns are not null and ID is >100?
It is easy to get the set of columns names in Oracle
SELECT DISTINCT COLUMN_NAME
FROM ALL_TAB_COLS, Table1
WHERE table_name = 'Table1 '
AND COLUMN_NAME LIKE 'Obs%' ;
But how can I combine this to something like this (in pseudo-code because the below does not work of course):
select * from Table1 Where ColName in ( SELECT DISTINCT COLUMN_NAME
FROM ALL_TAB_COLS, Table1
WHERE table_name = 'Table1 '
AND COLUMN_NAME LIKE 'obs%' )
And ColName.Value is Not Null and Table1.Id >100;
I know I can setup a query using dynamic sql, but is it possible to use some kind of transpose trick to obtain the result. I would prefer not to use PL-SQL if a simple query was available.
EDIT: solution with VIEW proposed is clever :) I should add that I would like to avoid adding Views, in addition, it would be really nice if I did not have to enumerate the cols by using a similar select as my selection of columns. This way the solution scales when new columns are added.
You could do it in SQL using xmlquery.
For example,
I want to search for the value KING in all the columns of all the tables in the entire SCOTT schema.
SQL> variable val varchar2(10)
SQL> exec :val := 'KING'
PL/SQL procedure successfully completed.
SQL> SELECT DISTINCT SUBSTR (:val, 1, 11) "Searchword",
2 SUBSTR (table_name, 1, 14) "Table",
3 SUBSTR (column_name, 1, 14) "Column"
4 FROM cols,
5 TABLE (xmlsequence (dbms_xmlgen.getxmltype ('select '
6 || column_name
7 || ' from '
8 || table_name
9 || ' where upper('
10 || column_name
11 || ') like upper(''%'
12 || :val
13 || '%'')' ).extract ('ROWSET/ROW/*') ) ) t
14 ORDER BY "Table"
15 /
Searchword Table Column
----------- -------------- --------------
KING EMP ENAME
SQL>
I have demonstrated few examples here.
In your case, add the filter AND COLUMN_NAME LIKE 'obs%' to filter the columns that you want to search for.
you could create a view which has all the columns concatenated together, so if this column is null then you know they are all null (bit messy but in theory would work). You may also be able to use the CALCULATED column functionality, but i'm not sure if this allows for non-numeric fields or not
dave