可以使用替换变量和SQL*Plus
column ... new_value ...
column col_width new_value col_width noprint
select greatest(nvl(max(length(head_results)), 0), length('head_results')) as col_width
from your_table;
column head_results format "a&col_width"
查询:
-
查找表中最长的值
max(length(head_results))
;
-
nvl(..., 0)
;
-
查找该值和固定字符串中的较大值
greatest(..., length('head_results'))
如果你愿意,你可以用固定值12;
-
并将表达式的结果作为别名
col_width
然后
column col_width new_value col_width noprint
列宽度
作为替换变量,它从查询继承值。
column head_results format "a&col_width"
将列宽设置为查询返回的字符数,使用替换变量-
a&col_width
已翻译为
a12
,或
a15
a68
或者别的什么。
当您进行实际查询时,该列将以该宽度显示。
使用虚拟表演示,最初只有一个短值,标题宽度为12个字符:
create table your_table (head_results varchar2(80));
insert into your_table (head_results)
values ('value_1');
1 row inserted.
set termout off
column col_width new_value col_width noprint
select greatest(nvl(max(length(head_results)), 0),
length('head_results')) as col_width
from your_table;
column head_results format "a&col_width"
set termout on
select head_results from your_table;
HEAD_RESULTS
------------
value_1
附加值越长,范围就越广:
insert into your_table (head_results)
values ('value_222222222');
1 row inserted.
set termout off
column col_width new_value col_width noprint
select greatest(nvl(max(length(head_results)), 0), length('head_results')) as col_width
from your_table;
column head_results format "a&col_width"
set termout on
select head_results from your_table;
HEAD_RESULTS
---------------
value_1
value_222222222
你的最长值仍然足够宽:
insert into your_table (head_results)
values ('value_99999999999999999999999999999999999999999999999999999999999999');
1 row inserted.
set termout off
column col_width new_value col_width noprint
select greatest(nvl(max(length(head_results)), 0), length('head_results')) as col_width
from your_table;
column head_results format "a&col_width"
set termout on
select head_results from your_table;
HEAD_RESULTS
--------------------------------------------------------------------
value_1
value_222222222
value_99999999999999999999999999999999999999999999999999999999999999