子查询缓存引发的问题

2462阅读 0评论2012-09-20 TOMSYAN
分类:Oracle

朋友要将一个表的一个列更新为2010年-2012年之间的随即日期。
 
采用的语句如下:
 
update a set datecol=(select trunc(sysdate,'yyyy')+dbms_random.value(-730,365) from dual);
 
但是这个语句却将日期更新为同一日期。
 

点击(此处)折叠或打开

  1. SQL> update a set datecol=(select trunc(sysdate,'yyyy')+dbms_random.value(-730,365) from dual);
  2. 12 rows updated.
  3. SQL> select * from a;
  4. datecol
  5. -------------------

  6. 2011/11/04 03:57:41
  7. 2011/11/04 03:57:41
  8. 2011/11/04 03:57:41
  9. 2011/11/04 03:57:41
  10. 2011/11/04 03:57:41
  11. 2011/11/04 03:57:41
  12. 2011/11/04 03:57:41
  13. 2011/11/04 03:57:41
  14. 2011/11/04 03:57:41
  15. 2011/11/04 03:57:41
  16. 2011/11/04 03:57:41
  17. 2011/11/04 03:57:41
  18. 12 rows selected.
这个问题是由于子查询缓存引起的,对于形如SELECT SUB_QUERY ,UPDATE WHERE SUB_QUERY之类的
子查询,oracle为了提高性能,只会执行一次。
如下:

点击(此处)折叠或打开

  1. SQL> select trunc(sysdate,'yyyy')+dbms_random.value(-730,365) ,(select trunc(sysdate,'yyyy')+dbms_random.value(-730,365) from dual) a from a;

  2. TRUNC(SYSDATE,'YYYY A
  3. ------------------- -------------------
  4. 2012/03/11 17:58:58 2011/05/11 17:13:07
  5. 2011/06/07 03:53:56 2011/05/11 17:13:07
  6. 2012/05/16 20:35:21 2011/05/11 17:13:07
  7. 2011/11/16 05:22:42 2011/05/11 17:13:07
  8. 2010/06/07 10:33:11 2011/05/11 17:13:07
  9. 2010/04/08 17:36:28 2011/05/11 17:13:07
  10. 2010/01/17 09:10:41 2011/05/11 17:13:07
  11. 2012/09/23 20:03:54 2011/05/11 17:13:07
  12. 2011/08/20 08:36:53 2011/05/11 17:13:07
  13. 2010/05/06 19:06:37 2011/05/11 17:13:07
  14. 2010/06/08 02:08:31 2011/05/11 17:13:07

  15. TRUNC(SYSDATE,'YYYY A
  16. ------------------- -------------------

  17. 2011/07/07 22:46:33 2011/05/11 17:13:07

  18. 12 rows selected.

正确的修改方法应该采用如下的方式:


点击(此处)折叠或打开

  1. SQL> update a set datecol= trunc(sysdate,'yyyy')+dbms_random.value(-730,365);

  2. 12 rows updated.

  3. SQL> select * from a;

  4. datecol
  5. -------------------

  6. 2012/09/24 09:08:39
  7. 2010/08/08 20:43:52
  8. 2011/06/04 14:13:52
  9. 2010/11/05 16:59:39
  10. 2010/11/27 06:49:07
  11. 2010/02/10 06:12:53
  12. 2011/09/02 21:18:47
  13. 2010/11/17 13:55:13
  14. 2011/10/22 09:37:32
  15. 2011/08/30 00:24:44
  16. 2011/02/06 05:54:38
  17. 2012/07/15 03:10:49

  18. 12 rows selected.



上一篇:11G新特性-控制文件延迟自动备份
下一篇:SQL30070N "Unsupported function for SPMDB connect" Command is not supported. SQLSTATE=5801