Oracle PL/SQL查詢語句有的時候要將number類型的欄位轉換成varchar2類型
在報表或頁面上經常會出現:
.440
.441
1.0
10.100
之類的資料,要不就是小數點前面的0被to_char或cast函數去掉了,或是末尾的無效小數位上的0沒有被去掉,很是鬧心。
jsp介面上還好處理,可以用類似下面的方法來處理:
Jsp代碼
- 體重:<ww:text name='format.num.3'><ww:param value='person.weight'/></ww:text>(Km)
體重:<ww:text name='format.num.3'><ww:param value='person.weight'/></ww:text>(Km)
但是在超級報表中,儲存格中要顯示的數字就不太好處理了,要將查詢出的欄位進行處理,
下面我總結了一下處理方法:
step1:格式化將小數點前的0保留、去掉末尾的0,去掉前面因格式化產生的多餘的空格:
Plsql代碼
- select t.num from(
- select ltrim(rtrim(to_char(0.44, '99990.000'), '0') , ' ') as num from dual union
- select ltrim(rtrim(to_char(0.441, '99990.000'), '0'), ' ') as num from dual union
- select ltrim(rtrim(to_char(1.0, '99990.0'), '0'), ' ') as num from dual union
- select ltrim(rtrim(to_char(10.100, '99990.000'), '0'), ' ') as num from dual
- )t
-
- /*
- 結果:
- 0.44
- 0.441
- 1.
- 10.1
- */
select t.num from( select ltrim(rtrim(to_char(0.44, '99990.000'), '0') , ' ') as num from dual union select ltrim(rtrim(to_char(0.441, '99990.000'), '0'), ' ') as num from dual union select ltrim(rtrim(to_char(1.0, '99990.0'), '0'), ' ') as num from dual union select ltrim(rtrim(to_char(10.100, '99990.000'), '0'), ' ') as num from dual)t/*結果:0.440.4411.10.1*/
step2:去掉可以多餘的小數點:
Plsql代碼
- select
- (case when instr(t.num,'.')=length(t.num) then rtrim(t.num,'.') else t.num end) as num
- from(
- select ltrim(rtrim(to_char(0.44, '99990.000'), '0') , ' ') as num from dual union
- select ltrim(rtrim(to_char(0.441, '99990.000'), '0'), ' ') as num from dual union
- select ltrim(rtrim(to_char(1.0, '99990.0'), '0'), ' ') as num from dual union
- select ltrim(rtrim(to_char(10.100, '99990.000'), '0'), ' ') as num from dual
- )t
-
- /*
- 結果:
- 0.44
- 0.441
- 1
- 10.1
- */