【问题标题】:Convert number to varchar2 in PLSQL without thousand separator in PLSQL在PLSQL中将数字转换为varchar2,而PLSQL中没有千位分隔符
【发布时间】:2020-01-14 06:04:57
【问题描述】:

有没有一种安全快速的方法将数字转换为 varchar2 而无需千位分隔符(无论排序规则或其他设置如何)。

例子:

/* Normal Collation */
1234.5 => '1234.5' (and not '1,234.5')
1.5 => '1.5'
/* Reverse Collation */
1234.5 => '1234,5' (and not '1.234,5')
1.5 => '1,5'

到目前为止我所拥有的是:

declare
  thousand_separator# varchar2(1);
begin
  thousand_separator# := nullif(substr(to_char(1000), 2, 1), 0);

  dbms_output.put_line(case when thousand_separator# is null then to_char(123456.123) else replace(to_char(123456.123), thousand_separator#) end);
end;

我正在寻找 to_char(<number>, 'CORRECT_FORMAT') 或类似类型的东西(不会添加任何前导零或尾随零)

【问题讨论】:

  • 在您的情况下,表达式thousand_separator# 永远不能为空,因为您通过nvl() 分配它。为什么你不能只使用不包含组分隔符的格式掩码(例如,'99999D99999' 在小数点分隔符的两边都有足够的 9,用于您希望看到的可能值范围 - as here)?跨度>
  • 是否存在默认无法正确显示的值?我唯一能立即想到的是 - 低于零(例如 0.5)的数字应该如何显示?
  • @AlexPoole 我的意思是写nullif 而不是nvl

标签: sql oracle plsql type-conversion


【解决方案1】:

可以使用the TM 'text minimum'格式模型:

文本最小数字格式模型返回(以十进制输出)可能的最小字符数。

虽然这是你默认得到的,但你使用to_char(),但无论如何都没有模型。

带小数点分隔符的演示:

alter session set nls_numeric_characters = '.,';

with t (num) as (
  select 1234.5 from dual
  union all
  select 1.5 from dual
  union all
  select 0.5 from dual
  union all
  select 0 from dual
  union all
  select 5 from dual
)
select to_char(num, 'TM') as str
from t;

STR                                                             
----------------------------------------------------------------
1234.5
1.5
.5
0
5

begin
  dbms_output.put_line(to_char(123456.123));
end;
/

123456.123
alter session set nls_numeric_characters = ',.';

with t (num) as (
  select 1234.5 from dual
  union all
  select 1.5 from dual
  union all
  select 0.5 from dual
  union all
  select 0 from dual
  union all
  select 5 from dual
)
select to_char(num, 'TM') as str
from t;

STR                                                             
----------------------------------------------------------------
1234,5
1,5
,5
0
5

begin
  dbms_output.put_line(to_char(123456.123));
end;
/

123456,123

【讨论】:

  • 给人的印象是to_char 依赖于排序规则和nls_numeric_characters。感谢您的澄清。
  • 根据docs,默认是TM9,和TM有区别吗?
  • 不,TM9 只是显式的 - TM 确实是 TM9 的简写。与 TMe 不同。
猜你喜欢
  • 1970-01-01
  • 2021-09-23
  • 1970-01-01
  • 1970-01-01
  • 2018-06-20
  • 1970-01-01
  • 2010-12-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多