Oracle SQL細節總結之constraint約束

simplewp發表於2012-09-16
1)約束constraints:在表上強加的約束條件,以保證資料的完整性;防止關聯表的資料丟失;
常見的約束型別:
        - NOT NULL
        - UNIQUE
        - PRIMARY KEY
        - FOREIGE KEY
        - CHECK

在表建立時,指定約束條件,也可在建立表後,再新增修改;約束條件分為列級或者表級;
REATE TABLE [schema.]table
        (column datatype [DEFAULT expr]
        [column_constraint],
        ...
        [table_constraint][,...]);

2)新增約束
ALTER TABLE table
              ADD [CONSTRAINT constraint] type (column);
3)刪除約束
ALTER TABLE table_name DROP CONSTRAINT constraint_name

4)重名約束
alter table table_name rename constraint old_name to new_name

5)約束有效/無效
alter table table_name enable/disable constraint constraint_name;
約束延期是一個對主鍵、唯一鍵等約束進行延遲檢查的功能。可以使用該功能將約束檢查延遲到事務提交時,而不是在進行DDL操作之後立即進行檢查。所以對約束檢查也有這兩個選項:延遲和立即

SQL> create table aaa
  2  (
  3   c1 number constraint aaa_pk primary key deferrable initially immediate,
  4   c2 number constraint c2_ck check(c2>10) deferrable initially immediate
  5  );

Table created.

SQL> set constraints c2_ck deferred;

Constraint set.

SQL> insert into aaa value (1,1);
insert into aaa value (1,1)
                       *
ERROR at line 1:
ORA-00928: missing SELECT keyword


SQL> insert into aaa values (1,1);

1 row created.

SQL> commit;
commit
*
ERROR at line 1:
ORA-02091: transaction rolled back
ORA-02290: check constraint (SCOTT.C2_CK) violated

提交時就會約束檢查,即延遲檢查;


6)檢視約束
user_constraints
user_cons_columns



來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/27009266/viewspace-743719/,如需轉載,請註明出處,否則將追究法律責任。

相關文章