只是把你的测试在一个单一的查询,并删除+10
(问题是不存在),这是你有什么:
SQL> with testCases(n) as (select 151 from dual union select 51 from dual)
2 select n,
3 substr(to_char(n, '099'),1,3) as substr_3,
4 substr(n,1,2) as substr_3
5 from testCases;
N SUBSTR_3 SUBSTR_3
---------- ------------ --------
51 05 51
151 15 15
我相信是什么让你期望一个不同的结果是to_char
应该做什么;澄清一下,看看下面的结果:
SQL> with testCases(n) as (select 151 from dual union select 51 from dual)
2 select n,
3 '|' || to_char(n, '099') || '|' as to_char
4 from testCases;
N TO_CHA
---------- ------
51 | 051|
151 | 151|
这里可以看到,to_char
添加一个空格所得到的字符串;这会使你的子字符串逻辑失效,给你意想不到的结果。 这种行为清楚地解释here:
额外的前导空格是潜在的减号。要删除 空间,您可以在格式
事实上使用FM,如果编辑格式掩码,您有
SQL> with testCases(n) as (select 151 from dual union select 51 from dual)
2 select n,
3 '|' || to_char(n, 'FM099') || '|' as to_char
4 from testCases;
N TO_CHA
---------- ------
51 |051|
151 |151|
和测试用例成为:
SQL> with testCases(n) as (select 151 from dual union select 51 from dual)
2 select n,
3 substr(to_char(n, 'FM099'),1,3) as substr_3,
4 substr(n,1,2) as substr_2
5 from testCases ;
N SUBSTR_3 SUBSTR_2
---------- ------------ --------
51 051 51
151 151 15
尝试'选择'|' || to_char(151,'099')|| '|' from dual',然后将格式掩码编辑为'FM099'';这应该可以帮助你找到问题 – Aleksej