ITPub博客

首页 > 应用开发 > IT综合 > 使用不含通配符的like运算符遇到char类型的字段时要注意!

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

原创 IT综合 作者:warehouse 时间:2008-04-19 19:17:38 0 删除 编辑
在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博客 ” ,链接:https://blog.itpub.net/19602/viewspace-1002747/ ,如需转载,请注明出处,否则将追究法律责任。

上一篇: 修改statistics!
请登录后发表评论 登录
全部评论

注册时间:2007-12-07

  • 博文量
    717
  • 访问量
    5366330