where子句中的数字错误无效

时间:2016-01-05 10:53:36

标签: sql oracle oracle11g

我在Oracle数据库中执行查询。列和一切都是正确的但我收到以下查询的无效数字错误:

select COUNT(*) AS "COUNT" from NE.STRUCT B
where B.STRUCT_TYPE in ('IDC') 
and NET_ENTITY_ID is not null 
and length(NET_ENTITY_ID) = 18 
AND regexp_like(SUBSTR(NET_ENTITY_ID,15,1),'[^A-Z]') 
and TO_NUMBER(SUBSTR(NET_ENTITY_ID,(length(NET_ENTITY_ID) -3), 4)) < 6000;

NET_ENTITY_ID字段只有一个数据ABCDEFGHXXXXNB0001

但并非必须始终拥有一个数据。这只是为了解决我正在考虑的问题。

错误讯息:

ORA-01722: invalid number
01722. 00000 -  "invalid number"
*Cause:    The specified number was invalid.
*Action:   Specify a valid number.

2 个答案:

答案 0 :(得分:2)

问题在于Oracle - 以及任何其他数据库 - 不保证WHERE中子句的评估顺序。您可以使用CASE

解决此问题
where B.STRUCT_TYPE in ('IDC') and
      NET_ENTITY_ID is not null and
      length(NET_ENTITY_ID) = 18 AND
      regexp_like(SUBSTR(NET_ENTITY_ID, 15, 1), '[^A-Z]') and 
      (CASE WHEN regexp_like(SUBSTR(NET_ENTITY_ID,(length(NET_ENTITY_ID) -3), 4), '^[0-9]{4}$'
            THEN TO_NUMBER(SUBSTR(NET_ENTITY_ID,(length(NET_ENTITY_ID) -3), 4)) 
       END) < 6000;

答案 1 :(得分:0)

在使用TO_NUMBER之前,您需要确保最后4个字符是数字。

这样做:

select COUNT(*) AS "COUNT" from 
( SELECT * FROM NE.STRUCT B
  where B.STRUCT_TYPE in ('IDC') 
  and NET_ENTITY_ID is not null 
  and length(NET_ENTITY_ID) = 18 
  AND regexp_like(SUBSTR(NET_ENTITY_ID,15,1),'[^A-Z]') 
  AND regexp_like(SUBSTR(NET_ENTITY_ID,-4),'[0-9]') 
)
where TO_NUMBER(SUBSTR(NET_ENTITY_ID,-4)) < 6000;

注意我简化了您的SUBSTR以获取最后4个字符。