我需要根据返回值的长度和列名的长度(在我的情况下是“ heads_results”)在SQL * Plus中格式化一个仓库。
select语句的结果:
head_results
**********************************************************
value_1
value_11
value_222222222
value_99999999999999999999999999999999999999999999999999999999999999
我需要根据任何行上返回的最大长度值(在这种情况下为length('value_99999999999999999999999999999999999999999999999999999999999999')
)来格式化“ head_results”列的长度。
如果没有返回值,或者返回的最大长度值小于length ('head_results')
,则将column_name的长度格式化为其长度。
在SQL * Plus中可以吗?
答案 0 :(得分:3)
您可以使用替换变量和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
允许您将col_width
用作替代变量,该变量将从查询中继承值。
然后,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