使用不含通配符的like运算符遇到char类型的字段时要注意!

在CBO下,oracle会把不含通配符的like表达式转为为等式,前提是like前面的字段类型必须是可变宽度字符类型的。当遇到char类型的字段时它不会这样做![@more@]

doc描述:

The optimizer simplifies conditions that use the LIKE comparison operator to compare an expression with no wildcard characters into an equivalent condition that uses an equality operator instead.

In the following example, the optimizer simplifies the first condition into the second:

last_name LIKE 'SMITH'

is transformed into

last_name = 'SMITH'

The optimizer can simplify these expressions only when the comparison involves variable-length datatypes. For example, if last_name was of type CHAR(10), then the optimizer cannot transform the LIKE operation into an equality operation due to the equality operator following blank-padded semantics and LIKE not following blank-padded semantics.

--===================================

SQL> desc tt
名称 是否为空? 类型
----------------------------------------- -------- ---------------------------

ID NUMBER(38)
NAME CHAR(2)

SQL> select * from tt;

ID NA
---------- --
1 m
2 m
3 m
4 m
5 m
6 n
1000 b
b

已选择8行。

SQL> select name,length(name) from tt;

NA LENGTH(NAME)
-- ------------
m 2
m 2
m 2
m 2
m 2
n 2
b 2
b 2

已选择8行。

SQL> select * from tt where name = 'n';

ID NA
---------- --
6 n

上面使用=之所以能查询出数据是因为n的后面填补了一个空格!之所以要填补是因为要查询的字符常量n的长度1小于name的数据类型char(2)的宽度2,所以在n的后面自动填补了一个空格。

SQL> select * from tt where name = 'n ';

ID NA
---------- --
6 n

上面的查询就没有自动填补空格,是因为要查询的字符常量是'n '后面已经有了空格,它的长度2等于name的类型char(2)的宽度。

SQL> select * from tt where name like 'n';

未选定行

上面的查询之所以没有查出数据,是因为oracle不会在like 后面的char类型的字符串常量中填补空格。

SQL> alter table tt modify name varchar2(2);

表已更改。

SQL> update tt set name=substr(name,1,1);

已更新8行。

SQL> commit;

提交完成。

SQL> select name,length(name) from tt;

NA LENGTH(NAME)
-- ------------
m 1
m 1
m 1
m 1
m 1
n 1
b 1
b 1

已选择8行。

SQL> select * from tt where name = 'n';

ID NA
---------- --
6 n

SQL> select * from tt where name like 'n';

ID NA
---------- --
6 n

来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/19602/viewspace-1002747/,如需转载,请注明出处,否则将追究法律责任。

转载于:http://blog.itpub.net/19602/viewspace-1002747/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值