简体   繁体   中英

Oracle To_Char function How to handle if it's already a string

Scenario: I am calling a function that returns a field that the user enters in. The field usually returns a number like '120000' which I then use to_char to convert into '120,000'.

Problem: Some users enter in values such as '120,000' which gives me an error when trying to use to_char. Also the function will return a space ' ' if no value is found. I tried something with to_number earlier and it has a problem with the ' ' I believe.

Question: What would be the best way to handle this problem? Case statement checking for the ','? Using to_number then to_char?

Note: I can hack a solution together I'm just wondering what the best way to handle this is.

Rather than using REPLACE you should use the more powerful REGEXP_REPLACE function. http://www.orafaq.com/wiki/REGEXP_REPLACE

You can then remove any non-numeric character from the string before then formatting it however you like.

In your case it would be something like:

REGEXP_REPLACE(<your field>, '[^0-9]+', '');

This replaces all non-numeric characters with null effectively removing them from the string.

See this answer too: Oracle: Replacing non-numeric chars in a string

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM