Reputation: 1345
Suppose I have a query like
select a.column1, b.column2, substr(b.column3,instr(b.column3,',')) as Column3
from tableA a, tableB b
where a.column1 = b.column1
How do I get the max character length for each column of this query ?
If tableA and tableB are defined as
tableA ( column1 VARCAHR2(100))
tableB ( column1 VARCAHR2(100), column2 INTEGER, column3 VARCAHR2(5000))
I would like to get those data :
COLUMN1 : 100
COLUMN2 : 10
COLUMN3 : 5000
Keep in mind this is a dynamic query, there might be any number of columns from any number of tables within limitation.
Upvotes: 1
Views: 1293
Reputation: 2715
You can create a table for a moment from your query (CTAS) and after that use user_tab_columns
to get column's data_length
for your new table.
create table temp as
select a.column1, b.column2, substr(b.column3,instr(b.column3,',')) as Column3
from tableA a, tableB b
where a.column1 = b.column1
--No need for store the data, unless you want the maximum size of current data.
and 1 = 0;
select column_name, data_length from user_tab_columns where table_name = 'TEMP';
drop table temp;
It's quite easy and you do not need to care what you have exactly in your query. Oracle will figure out this for you.
BTW. The max size of VARCHAR2
is 4000. You cannot have 5000 unless you are using 12c with extended data types.
Upvotes: 2
Reputation: 1682
You might have to access the USER_TAB_COLUMNS
metadata table to get these column lengths
Below is an example query
SELECT COLUMN_NAME
,CHAR_LENGTH
FROM USER_TAB_COLUMNS
WHERE TABLE_NAME IN ('tableA', 'tableB')
AND COLUMN_NAME IN ('column1', 'column2', 'column3')
;
If you need the above in your generated query, then it would need to change to something like below
select a.column1
, b.column2
, substr(b.column3,instr(b.column3,',')) as Column3
, (SELECT CHAR_LENGTH FROM USER_TAB_COLUMNS WHERE TABLE_NAME = 'tableA' AND COLUMN_NAME = 'column1') AS column1_size
, (SELECT CHAR_LENGTH FROM USER_TAB_COLUMNS WHERE TABLE_NAME = 'tableB' AND COLUMN_NAME = 'column2') AS column2_size
, (SELECT CHAR_LENGTH FROM USER_TAB_COLUMNS WHERE TABLE_NAME = 'tableB' AND COLUMN_NAME = 'column3') AS column3_size
from tableA a
, tableB b
where a.column1 = b.column1
The above is one way of doing this just as an example. Depending on what you are trying to do and how you are generating the query, I think you would want to get the column sizes in a separate query like the first one, since you already know the column and table names when generating the query.
Hope this helps..
Upvotes: 0