神秘的 ORACLE DUAL
2024-08-29 13:37:32
供稿:網友
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 right">(出處:清風軟件下載學院)