1.建立一張表格
create table test(id number,name varchar2(20),class_name varchar2(20));
1.1建立表格的時候直接建立主外鍵
create table test(id number primary key,name varchar2(20) constraint t_fk references table_name(column_name));
create table test(id number,name varchar2(20)
constraint pk primary key(id),
constraint fk foreign key(id) references 關聯表(關聯表主鍵);
--增加主鍵
alter table test add constraint constraint_name primary key(column_name);
--增加外鍵
alter table test add constraint constraint_name foreign key(column_name) references 關聯表(column_name);--這裡需要注意一個表的外鍵必須是另一個表的主鍵
--增加唯一索引
create unique index index_name on table_name(column_name);
--修改列的屬性
alter table test modify column_name varchar2(10);--如果以前column_name varchar2(20);
--修改表的名稱
rename table_name to table_name;
--為列設定預設值
alter table test modify name varchar2(20) default 'hello');--這個不會影響已經插入的資料隻會對新資料造成影響
create table test (id number default 2);
--增加check
alter table test add constraint ck check ((id>20) and (id <30));
alter table test add constraint ck check(name in ('hello','world');
--unique
alter table test add constraint cuq unique(id);
--修改列的預設值
alter table test modify id default sysdate+1;
--添加列
alter table test add class varchar2(20);
alter table test add user varchar2(20) unique not null;
--删除列
alter table test drop column class;
--對表添加注釋
commont on table test is '測試表';
--對列添加注釋
commont on column table.id is '主鍵';
--删除表
drop table test;
--清除表的資料
truncate table test;
delete from test;
truncate 操作與 delete 操作對比差別
操作 | 復原 | 高水線 | 空間 | 效率 |
Truncate | 不能 | 下降 | 回收 | 快 |
delete | 可以 | 不變 | 不回收 | 慢 |
也就是說我們delete掉一個表格時其表格所占用的表空間時不會釋放的。
--禁用限制
alter table test disable constraint constraint_name;
--啟用限制
alter table test enable constraint constraint_name;
--延遲限制
alter table test drop constraint constraint_name;
alter table test add constraint constraint_name foreign key(id) references table_name(column_name) deferrable initially deferred;
deferrable的兩個選項差別
deferrable表示該限制是可延遲驗證的. 它有兩個選項:
Initially immediate(預設): 立即驗證, 執行完一個sql後就進行驗證;
Initially deferred: 延遲驗證, 當事務送出時或調用set constraint[s] immediate語句時才驗證.
差別是: 事務送出時驗證不通過, 則立即復原事務; set constraint[s] immediate時隻驗證, 不復原事務.
not deferrable與deferrable差別
差別就在于: “立即驗證的可延遲限制” 是可以根據需要設定成 “延遲驗證的可延遲限制”的, 而“不可延遲驗證”是不能改變的.
最後我們如果想檢視我們對test表格建立了那些限制以及限制所對應的列
可以通過檢視user_constraints and user_cons_columns;
來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/26509390/viewspace-1391373/,如需轉載,請注明出處,否則将追究法律責任。
轉載于:http://blog.itpub.net/26509390/viewspace-1391373/