最近數據處理時經常發現有數字中含有大量字符,執行過程報“ORA-01722: invalid number”異常,可以有一下幾種方法去除:
1、replace 用法簡單,寫法較復雜,只能處理已知字符
With test_table1 As ( Select 1 seq_num, '2134?654?ag d35' strings From dual Union All Select 2 seq_num, '651 354a g5 dd21' strings From dual ) Select seq_num, Replace(Replace(Replace(Replace(Replace(strings, '?', ''), 'a', ''), 'g', ''), 'd', ''), ' ', '') From test_table1; ---執行結果 1 213465435 2 651354521
2、translate 用法簡單,寫法簡單,只能處理已知字符,字符串、待查找字符,替換字符,均不能為null,否則返回null,字符串按查找順序替換,若無則去除
With test_table1 As ( Select 1 seq_num, '2134?654?ag d35' strings From dual Union All Select 2 seq_num, '651 354a g5 dd21' strings From dual ) Select seq_num, translate(strings, '1asdfasg ?', '1') From test_table1; ---執行結果 1 213465435 2 651354521
3、regexp_replace 正則表達式 增強型replace 參數多,可根據正則式處理所有字符
With test_table1 As ( Select 1 seq_num, '2134?654?ag d35' strings From dual Union All Select 2 seq_num, '651 354a g5 dd21' strings From dual Union All Select 3 seq_num, '2134654?ag d35' strings From dual Union All Select 4 seq_num, '16?54?aasdgf78as' strings From dual Union All Select 5 seq_num, '16?!@#$%^&*()~:"+_?><|~8as' strings From dual ) Select seq_num, regexp_replace(strings, '[^0-9]', '') From test_table1; ---執行結果 1 213465435 2 651354521 3 213465435 4 165478 5 168
