神秘的DUAL
2024-07-21 02:08:38
供稿:网友
dual ? 有什么神秘的? 当你想得到oracle系统时间, 简简单单敲一行sql
不就得了吗? 故弄玄虚….
sql> select sysdate from dual;
sysdate
---------
28-sep-03
哈哈, 确实dual的使用很方便. 但是大家知道dual倒底是什么object, 它有什么特殊的行为吗? 来,我们一起看一看.
首先搞清楚dual是什么object :
sql> connect system/manager
connected.
sql> select owner, object_name , object_type from dba_objects where object_name like '%dual%';
owner object_name object_type
--------------- --------------- -------------
sys dual table
public dual synonym
原来dual是属于sys schema的一个表,然后以public synonym的方式供其他数据库user使用.
再看看它的结构:
sql> desc dual
name null? type
----------------------------------------- -------- ----------------------------
dummy varchar2(1)
sql>
只有一个名字叫dummy的字符型column .
然后查询一下表里的数据:
sql> select dummy from dual;
dummy
----------
x
哦, 只有一条记录, dummy的值是’x’ .很正常啊,没什么奇怪嘛. 好,下面就有奇妙的东西出现了!
插入一条记录:
sql> connect sys as sysdba
connected.
sql> insert into dual values ( 'y');
1 row created.
sql> commit;
commit complete.
sql> select count(*) from dual;
count(*)
----------
2
迄今为止,一切正常. 然而当我们再次查询记录时,奇怪的事情发生了
sql> select * from dual;
dummy
----------
x
刚才插入的那条记录并没有显示出来 ! 明明dual表中有两条记录, 可就是只显示一条!
再试一下删除 ,狠一点,全删光 !
sql> delete from dual; /*注意没有限定条件,试图删除全部记录*/
1 row deleted.
sql> commit;
commit complete.
哈哈,也只有一条记录被删掉,
sql> select * from dual;
dummy
----------
y
为什么会这样呢? 难道sql的语法对dual不起作用吗?带着这个疑问, 我查询了一些oracle官方的资料. 原来oracle对dual表的操作做了一些内部处理,尽量保证dual表中只返回一条记录.当然这写内部操作是不可见的 .
看来oracle真是蕴藏着无穷的奥妙啊!
附: oracle关于dual表不同寻常特性的解释
there is internalized code that makes this happen. code checks that ensure
that a table scan of sys.dual only returns one row. svrmgrl behaviour is
incorrect but this is now an obsolete product.
the base issue you should always remember and keep is: dual table should always
have 1 row. dual is a normal table with one dummy column of varchar2(1).
this is basically used from several applications as a pseudo table for
getting results from a select statement that use functions like sysdate or other
prebuilt or application functions. if dual has no rows at all some applications
(that use dual) may fail with no_data_found exception. if dual has more than 1
row then applications (that use dual) may fail with too_many_rows exception.
so dual should always have 1 and only 1 row