user1751356
user1751356

Reputation: 615

Oracle data type conversion issue with to_number function

I ran across a weird scenario where to_number function is not being able to convert the numbers stored in string data type column in one database but not in another.

So, to rule out all possible scenarios such as additional spaces, nulls, junk etc, I have selected only one single and applied to_number function on the column and I totally this is not the best practice saving numbers as strings.

Interestingly, the query executes fine in one database but in others.

The below query runs fine in development but in test database.

select column_name 
from table_name 
where to_number(column_name) = 1618

Also, when i run the below query in test, I get results with out any error.

select to_number(column_name) from table_name 

When I move the to_number function to where clause, that is when I'm getting invalid number error.

Any thoughts?

Thanks...

Upvotes: 0

Views: 3304

Answers (1)

Justin Cave
Justin Cave

Reputation: 231861

The problem is almost certainly that in the database that throws an error, you have at least one row that has a string value that cannot be converted to a number. The simplest way to find that row is generally to do something like

CREATE FUNCTION is_number( p_str IN VARCHAR2 )
  RETURN VARCHAR2
IS
  l_num NUMBER;
BEGIN
  l_num := to_number( p_str );
  RETURN 'Yes';
EXCEPTION
  WHEN others 
  THEN
    RETURN 'No';
END;

and then

SELECT column_name
  FROM table_name
 WHERE is_number( column_name ) = 'No';

As to why

SELECT to_number( column_name )
  FROM table_name

works, are you certain that you are fetching every row? Most tools will only fetch the first, say, 50 rows when you run a query and wait for the user to request more data before the database continues executing the query. Assuming that the invalid data is on row 10,001, Oracle would happily return the first 10,000 rows successfully and then throw an error when a request was made to fetch row 10,001.

Upvotes: 2

Related Questions