經常使用dual,都忘了是什麼意思了,再找來溫習一下
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