Can I pass a number for varchar2 in Oracle?

☆樱花仙子☆ 提交于 2019-12-01 06:24:27
JAQFrost

The problem is that you expect that Oracle will implicitly cast 1234 to a character type. To the contrary, Oracle is implicitly casting the column to a number. There is a non-numeric value in the column, so Oracle throws an error. The Oracle documentation warns against implicit casts just before it explains how they will be resolved. The rule which explains the behaviour you're seeing is:

When comparing a character value with a numeric value, Oracle converts the character data to a numeric value.

Oh, it is much better to convert to char rather than to numbers:

select *
from table
where col1 = to_char(1234)

When the col1 does not look like a number, to_number returns an error, stopping the query.

Oracle says invalid number. Why is that? Why I cannot pass a number when it is varchar2?

Oracle does an implicit conversion from character type of col1 to number, since you're comparing it as a number.

Also, you assume that 1234 is the only row that's being fetched. In reality, Oracle has to fetch all rows from the table, and then filter out as per the where clause. Now there's a character value in col1 that's being fetched before it encounters your 1234 row & that's causing the error, since the character cannot be converted to a number.

This fiddle shows the behaviour. Since abc canot be converted to a number, you get that error message


Now if the only record in the table is that of col1 containing a numeric character, you'll see that the statement will work fine

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!