如果可以明确的使用日期常量来表示,那么就尽量避免使用SYSDATE作为替代。以前写过一篇SQL中如何处理常量的,其实已经包含了这个含义。
sql语句中常量的处理:http://yangtingkun.itpub.net/post/468/20038
有时候出于偷懒的目的,有些人习惯在应该输入常量的地方使用类似SYSDATE的函数来代替,但是这会带来额外的性能代价:
[oracle@yans1 ~]$ sqlplus test/test
SQL*Plus: Release 10.2.0.3.0 - Production on 星期二 7月 14 10:00:52 2009
Copyright (c) 1982, 2006, Oracle. All Rights Reserved.
Connected to:
Oracle Database 10g Enterprise Edition Release 10.2.0.3.0 - 64bit Production
With the Partitioning, OLAP and Data Mining options
SQL> set pages 100 lines 120
SQL> create table t (id number, name varchar2(30), created date);
Table created.
SQL> insert into t select rownum, object_name, created from dba_objects;
70739 rows created.
SQL> insert into t select * from t;
70739 rows created.
SQL> insert into t select * from t;
141478 rows created.
SQL> insert into t select * from t;
282956 rows created.
SQL> insert into t select * from t;
565912 rows created.
SQL> insert into t select * from t;
1131824 rows created.
SQL> insert into t select * from t;
2263648 rows created.
SQL> insert into t select * from t;
4527296 rows created.
SQL> commit;
Commit complete.
SQL> set timing on
SQL> select count(*) from t where created >= to_date('2009-1-1', 'yyyy-mm-dd');
COUNT(*)
----------
744960
Elapsed: 00:00:00.56
SQL> select count(*) from t where created >= to_date('2009-1-1', 'yyyy-mm-dd');
COUNT(*)
----------
744960
Elapsed: 00:00:00.40
SQL> select count(*) from t where created >= trunc(sysdate, 'yyyy');
COUNT(*)
----------
744960
Elapsed: 00:00:01.58
SQL> select count(*) from t where created >= trunc(sysdate, 'yyyy');
COUNT(*)
----------
744960
Elapsed: 00:00:01.54
上面两个SQL等价,但是使用常量方式所需的执行时间,仅是使用SYSDATE函数的1/3左右。这时由于对于常量的计算,Oracle只需要在执行前运行一次得到结果就可以了,但是对于SYSDATE函数,则需要在与每条记录进行比较的时候都进行调用。
不仅仅是SYSDATE函数,其他函数也是一样的道理。应该只是在需要的时候进行调用:
SQL> select count(*) from t where name = 'TEST';
COUNT(*)
----------
768
Elapsed: 00:00:00.32
SQL> select count(*) from t where name = 'TEST';
COUNT(*)
----------
768
Elapsed: 00:00:00.31
SQL> select count(*) from t where name = user;
COUNT(*)
----------
768
Elapsed: 00:00:00.58
SQL> select count(*) from t where name = user;
COUNT(*)
----------
768
Elapsed: 00:00:00.57
来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/4227/viewspace-609180/,如需转载,请注明出处,否则将追究法律责任。
转载于:http://blog.itpub.net/4227/viewspace-609180/