十四、ORACLE五種約束的使用
阿新 • • 發佈:2018-12-02
ORACLE五種約束的使用
1、唯一性約束
新增惟一性約束 ALTER TABLE USERS ADD CONSTRAINT UQ_EMAIL UNIQUE (EMAIL) 刪除惟一性約束 ALTER TABLE USERS DROP CONSTRAINT UQ_EMAIL 重新命名惟一性約束 ALTER TABLE USERS RENAME CONSTRAINT SYS_C005188 TO UQ_EMAIL 禁用/啟用惟一性約束 ALTER TABLE USERS DISABLE CONSTRAINT UQ_EMAIL
2、非空約束
方式1.在建立表的時候就約束非空,如下:
create table student (
id number(5) primary key,
name varchar2(20) not null
);
方式2.對於已存在的表新增非空約束,如下:
alter table student modify name not null;
3、主鍵約束
為表新增多列主鍵
ALTER TABLE EMP ADD CONSTRAINT PK_EMP PRIMARY KEY(EMP_ID,EMP_NAME)
4、外來鍵約束
CREATE TABLE CUSTOMERS ( CUSTOMER_ID NUMBER, CUSTOMER_NAME VARCHAR(20), CONSTRAINT PK_CUSTOMERS PRIMARY KEY(CUSTOMER_ID) ) CREATE TABLE ORDERS ( ORDER_ID NUMBER, CUSTOMER_ID NUMBER, PRODUCT_NAME VARCHAR(20), QUANTITY NUMBER, CONSTRAINT PK_ORDERS PRIMARY KEY(ORDER_ID) ) ALTER TABLE ORDERS ADD CONSTRAINT FK_ORDERS_CUSTOMERS FOREIGN KEY(ORDER_ID ) REFERENCES CUSTOMERS(CUSTOMER_ID)
5、檢查約束
新增檢查約束
ALTER TABLE STUDENTS ADD CONSTRAINT CK_STUDENT_NAME CHECK (LENGTH(STUDENT_NAME) <= 4)
ALTER TABLE STUDENTS ADD CONSTRAINT CK_SEX CHECK (SEX IN ('男','女'))