首页 > 解决方案 > SQL*Plus 中的条件列格式

问题描述

我需要根据返回值的长度和列名的长度(在我的例子中是“heads_results”)来格式化 SQL*Plus 中的 repot。

选择语句的结果:

head_results
**********************************************************
value_1 
value_11
value_222222222
value_99999999999999999999999999999999999999999999999999999999999999

我需要根据任何行(在本例中)返回的最大长度值来格式化列“head_results”的长度length('value_99999999999999999999999999999999999999999999999999999999999999')。如果没有返回值或返回的最大长度值小于length ('head_results')然后将 column_name 的长度格式化为其长度。

在 SQL*Plus 中是否可行?

标签: oraclesqlplus

解决方案


您可以使用替换变量和 SQL*Pluscolumn ... 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, or a15, or 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

推荐阅读