首先,关于字符常量的比较规则,在这里说一下,有两种,一种是自动填充空格,一种是不自动填充空格
1,自动填充空格:比较两个字符串的时候,如果长度不一致,那么会在长度短的字符串最后填补空格到相同长度,比较顺序是从左到右。这种比较规则局限于字符常量,char,nchar,user函数的返回值。
2,不自动填充空格:比较两个字符串,还是从左到右,遇到大的就大了,如果比较比较到短的都比完了还没有更大的,那么长的大。比如 字符串'86'>'85999'。这种比较规则适用于varchar2,nvarchar2。
举例如下:
SQL> select 1 from dual where 'test'=' test';
no rows selected
SQL> select 1 from dual where 'test'='test ';
1
----------
1
SQL> select 1 from dual where 'test'='test ';
1
----------
1
可以发现,空格在右边是相等的,但是空格在左边就不相等,因为oracle从左往右比,从右边填空格,而不会从左边填。
关于char的测试如下:
SQL> create table t1(a char(10));
Table created.
SQL> create table t2(b varchar2(10));
Table created.
SQL> insert into t1 values('test');
1 row created.
SQL> insert into t2 values('test');
1 row created.
SQL> commit;
Commit complete.
SQL> select a from t1 where a='test';
A
----------
test
SQL> select * from t1,t2 where trim(a)=b;
A B
---------- ----------
test test
SQL> select * from t1 where a=' test';
no rows selected
SQL> select * from t2 where b=' test';
no rows selected
无论char还是varchar2,前面右空格的都不会相等。
SQL> select * from t1 where a= 'test ';
A
----------
test
SQL> select * from t2 where b= 'test ';
no rows selected
但是呢,char的比较可以自动填空格,varchar2不行。
SQL> select * from t1,t2 where trim(a)=b;
A B
---------- ----------
test test
SQL> select * from t1,t2 where a=rpad(b,10);
A B
---------- ----------
test test
得这样才能相等,是不是很麻烦呢?嗯,是的。因为这样的话,那么就是隐式转换了,索引就有可能因为这个用不上,所以一般在设计表的时候,我们都会建议客户,number,date,varchar2等字段合理用好就够了,不要用用char,long等一些难整的字段类型。
另外,在绑定变量,plsql中,也存在这个问题,比如,绑定变量你用char(10)去声明,那么你的值不够10位,会查询不到数据的,plsql也是同理。
不多说,反正char这个玩意能不用就不用~~
SQL> select * from t1 where a=' test';
no rows selected
SQL> select * from t2 where b=' test';
no rows selected
无论char还是varchar2,前面右空格的都不会相等。
SQL> select * from t1 where a= 'test ';
A
----------
test
SQL> select * from t2 where b= 'test ';
no rows selected
SQL> select * from t1,t2 where a=b;
no rows selected
关联查询,没有结果,,因为呢:char与varchar2比较,会先转换为varchar2在比较。SQL> select * from t1,t2 where trim(a)=b;
A B
---------- ----------
test test
SQL> select * from t1,t2 where a=rpad(b,10);
A B
---------- ----------
test test
得这样才能相等,是不是很麻烦呢?嗯,是的。因为这样的话,那么就是隐式转换了,索引就有可能因为这个用不上,所以一般在设计表的时候,我们都会建议客户,number,date,varchar2等字段合理用好就够了,不要用用char,long等一些难整的字段类型。
另外,在绑定变量,plsql中,也存在这个问题,比如,绑定变量你用char(10)去声明,那么你的值不够10位,会查询不到数据的,plsql也是同理。
不多说,反正char这个玩意能不用就不用~~
来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/30123160/viewspace-2058851/,如需转载,请注明出处,否则将追究法律责任。
转载于:http://blog.itpub.net/30123160/viewspace-2058851/
5万+

被折叠的 条评论
为什么被折叠?



