定义如下:
kbn char(1);
nymd char(7);
begin
kbn := ' ';
nymd := ' ';
if (kbn = nymd) then
-- dbms.output 'aaaa'
else
-- dbms.output 'bbbbb'
end if;
end;
结果输出的是aaaa ,为什么呢? kbn 和nymd定义的长度是不一样的啊,怎么比较的时候,返回true呢?
请高手解释说明下。。。
------解决方案--------------------
char类型与char型或字符常量的比较,在比较时使用补齐空格的方式进行比较。
------解决方案--------------------
这个是比较的规则,与你定义的长度没关系。
char不同于varchar2。
varchar2类型与varchar2类型,char型和字符常量的比较,在比较时不补充空格,直接比较。
------解决方案--------------------
一个空格和多个空格是一样的!
------解决方案--------------------
是的,是将两个串长度补成一致以后再进行比较,与定义无关。
------解决方案--------------------
刚试的时候,吓了我一跳
做了下测试:
--1个空格和2个空格竟然真的相等了
SQL> select * from dual where ' '=' ';
DUMMY
-----
X
--同样,'1'和'1 '也会相等
SQL> select 1 from dual where ' 1 1'=' 1 1 ';
1
----------
1
--可以认为,在等式两端直接用字符串来比较,会被解析成char类型,比较时会根据较长的那个来匹配,自动补上空格
--创建一张测试表,看看系统会为'1 '给什么类型
SQL> create table tmp_1 as select '1 ' c from dual ;
Table created
SQL> desc tmp_1
Name Type Nullable Default Comments
---- ------- -------- ------- --------
C CHAR(2) Y
SQL> alter table tmp_1 add c1 char(7) default '1';
Table altered
SQL> select * from tmp_1 where c=c1;
C C1
-- -------
1 1
--上面的是两个char类型的字符串进行比较,如果是varchar2呢
SQL> select * from tmp_1 where cast(c as varchar2(2))=c1;
C C1
-- -------
--不等了。当等式一端的字符串是varchar2类型,则按变长字符串来比较
SQL>
这是个很奇特的问题
在metalink上找到这么一段解释:
Applies to:
PL/SQL - Version: 10.2.0.4
This problem can occur on any platform.
Symptoms
When attempting to execute a PLSQL block which uses equality operator with space padded literals
gives different result on 9.2.0.8 and 10+ release
Sample 1 :
set serveroutput on
begin
If 'ABCD'
------解决方案--------------------
' ' = 'ABCD' THEN --concatenate with a space
dbms_output.put_line ('equal');
else
dbms_output.put_line ('different');
end if;
end;
/
Sample2 :
set serveroutput on
begin
If 'ABCD ' = 'ABCD' THEN
dbms_output.put_line ('equal');
else
dbms_output.put_line ('different');
end if;
end;
/
Sample Output :
表格见下图
Cause
The cause of this problem has been identified in
Bug 4872783 : No space-pad in comparing with concatinated variables
In releases between 8.0 and 9.2, the result of a string concatenation operation was always of type CHAR. However, beginning in 10.1, the result type was always VARCHAR2. This is generally only of importance when the result is not immediately assigned into a variable, but is used directly in an expression sensitive to the type of its arguments. In particular, '=' (comparison) returns different values depending on the types of its arguments.
The 'ABCD ' = 'ABCD' is always treated as a comparison between CHAR 'ABCD ' and CHAR 'ABCD' - these are treated as equal because when doing CHAR comparison we pad all values out to the same