简体   繁体   English

带有to_number函数的Oracle数据类型转换问题

[英]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. 我遇到了一个奇怪的场景,其中to_number函数无法转换存储在一个数据库中的字符串数据类型列中的数字,而不能转换为另一个数据库中的数字。

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. 因此,为了排除所有可能的场景,例如额外的空格,空值,垃圾等,我在列上只选择了一个单独的并应用了to_number函数,而这完全不是将数字保存为字符串的最佳做法。

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. 当我将to_number函数移动到where子句时,就是我收到无效数字错误。

Any thoughts? 有什么想法吗?

Thanks... 谢谢...

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. 在运行查询时,大多数工具只会获取第一行,比如50行,并等待用户在数据库继续执行查询之前请求更多数据。 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. 假设无效数据在第10,001行,Oracle很乐意成功返回前10,000行,然后在请求获取行10,001时抛出错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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