ORACLE 表char欄位混合儲存數字和字母類似資料時按數字的where條件查詢報錯ORA-01722

清風艾艾發表於2019-01-28

    ORACLE 資料庫,建立有char欄位列的資料表:create table tbl_c (id char(1));

對該表插入字元'1'、數字2,執行查詢:

select * from  tbl_c;SQL語句能夠正常執行,

select * from  tbl_c where id=1;SQL語句能夠 正常 執行;

表中插入字元'A’,

select * from  tbl_c;SQL語句能夠 正常 執行

select * from  tbl_c where id=1;SQL語句查詢時報錯 ORA-01722: invalid number 

刪除插入的字元資料'A'後,查詢恢復正常;

    實驗如下:

1、建立實驗表

SQL> create table tbl_c (id char(1));

Table created.


2、插入實驗 正常 資料

SQL> insert into tbl_c values('1');

1 row created.

SQL> insert into tbl_c values(2);

1 row created.

SQL> commit;

Commit complete.


3、測試查詢

SQL> select * from tbl_c;

I

-

1

2

SQL>  select * from  tbl_c where id=1;

I

-

1

SQL> 


4、插入影響CBO條件查詢解析執行的資料

SQL> insert into tbl_c values('A');

1 row created.

SQL> commit;

Commit complete.

SQL> 


5、測試查詢,where條件查詢數字查詢出現異常

SQL> select * from  tbl_c where id='A';

I

-

A

SQL> select * from  tbl_c where id='2';

I

-

2

SQL> 

SQL> select * from  tbl_c where id=1;

ERROR:

ORA-01722: invalid number

no rows selected

    關於這種現狀,ORACLE MOS文件 Doc ID 1059215.1 有相關說明:

CAUSE

The problem is due to the way Oracle handles datatype conversions.
The statement being executed is made to compare the VARCHAR database field with a numeric literal value.
In this case, the database does an implicit conversion applying the TO_NUMBER function to the first column, in order to be able to perform the comparison between comparable values.
If this column contains non-numeric values and one of them is retrieved and the condition is evaluated, the ORA-1722 error is issued.

SOLUTION

The proposed solution is to avoid the implicit conversion. This may be achieved in two ways:
A) Modify the data to assure no invalid numeric values are stored in the column, either updating invalid column values or modifying the column datatype to enforce the presence of only numeric values. This implies the application remains unchanged.
This solution implies a modification in the database model, or to add restrictions not necessarily applicable to the table column involved.

OR

B) Modify the application to ensure the comparison is done between two VARCHAR values. This may be easily achieved surrounding the variable value with quotes:

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/29357786/viewspace-2564991/,如需轉載,請註明出處,否則將追究法律責任。

相關文章