现在的位置: 首页 > 综合 > 正文

Oracle创建表

2013年11月29日 ⁄ 综合 ⁄ 共 2563字 ⁄ 字号 评论关闭
 创建表

CREATE [ GLOBAL TEMPORAY ] TABLE  table_name (

column_name Type [CONSTRAINT constraint_def DEFAULT default_exp][,column_name type [CONSTRAINT constraint_def DEFAULT default_exp]]

[ON COMMIT { DELETE | PRESERVE } ROW]

TABLESPACE tablespace_name;

其中,GLOBAL TEMPORAY说明该表的行都是临时的,这种表就称为临时表。行的有效性由ON COMMIT指定。临时表对于所有会话都是可见的。

conn dubing/lover;

create table order_status(

                id integer constraint pk_order_status_id primary key,

                status varchar2(10),

                last_modified date default sysdate

           );

 

1、修改表

添加一个字段

alter table student add classid number(2);

修改字段的长度

alter table modify sname varchar(30);

删除字段:一般在工作时,轻易不要随便删除一个认为可有可无的字段。

alter table student drop colomn sal;

修改表的名字

rename student to stu

删除表

drop table student;

2、 删除数据

delete from :删除所有记录,表结构还在,写日志,可以恢复的,速度慢。

drop table:删除表的结构和数据,无法恢复。

truncate talbe:清空表,表的结构在,不写日志,无法找回删除的记录,删除速度快。

3、获得有关表的信息

对表执行describe命令

查询user_tables,它是数据字典的一部分。

查询all_tables,查询当前用户可以访问的所有表信息

4、添加约束

--添加NOT NULL约束,凉意这里使用的是modify

alter table t_order_status

modify status constraint nn_order_status_status NOT NULL;

--添加外键约束

alter table t_order_status

add constraint fk_order_status_modified_by foreign key (modified_by)  references t_employee(id);

--使用一个带有foreign key 约束的on delete cascade子句,可以指定在父表中删除一行记录时,子表中匹配的所有行也都将被删除。

alter table t_order_status

drop constraint fk_order_status_modified_by;         

alter table t_order_status

add constraint fk_order_status_modified_by foreign key(modified_by )references t_employee(id) on delete cascade;

--使用一个带有foreign key 约束的on delete set null子句,可以指定在父表中删除一行记录,子表中匹配的行的键值设置为NULL。

alter table t_order_status

drop constraint fk_order_status_modified_by          

alter table t_order_status

add constraint fk_order_status_modified_by foreign key (modified_by) references t_employee(id) on delete set null;

--查看约束信息user_constraints、all_constraints

select * from user_constraints where table_name='t_order_status';

--添加UNIQUE约束

alter table t_order_status

add constraint uq_order_status_status UNIQUE (status);

--禁用约束

/*默认情况下,约束在创建时是启用的。在创建约束时可以在constraint子句的末尾添加disable来禁用约束*/

alter table t_order_status

drop constraint uq_order_status_status       

alter table t_order_status

add constraint  uq_order_status_status UNIQUE(status) disable;

/*使用disable constraint 子句可以禁用现有的约束*/

alter table t_order_status

disable constraint fk_order_status_modified_by

--启用约束

/*使用enable constraint 子句可以启用现有的约束,要启用约束,表中所有的行必须满足约束条件。*/

       alter table t_order_status

       enable constraint fk_order_status_modified_by

/*通过指定enable novalidate constraint 可以选择只对新数据满足某个约束*/

       alter table t_order_status

       enable novalidate constraint fk_order_status_modified_by

 

--获得有关列的约束信息user_cons_columns

select * from user_cons_columns where table_name='t_order_status';

 --重命名表

rename t_order_status2 to t_order_status

抱歉!评论已关闭.