oracle数据库常用语句汇总1(建表)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/william_zhangsun/article/details/78028446

1.oracle建表语句

create  table  student(id int,name varchar2(10),score number(4,1));

其中create table是固定语法,create table +表名+字段,这样新建的表在当前库中,如果需要指定数据库,可以在表名前面加上数据库名称,比如create table test.student()。有时会给数据库中的字段添加注释,可以使用comment on column student.id is '学号'.

2.oracle添加主外键

主外键的添加一般可以在建表时添加,也可以在表建好之后进行添加。

首先我们说下在建表时就建立主键,具体语句如下:create table student(id int primary key not null,name varchar2(10)...),如果另外一张表关联student表的主键,也就是所说的外键,可以在建表时这样写:create  table score(studentno numbber references student(id)),这样两张表就通过主外键联系起来。也可以在表建好之后,添加主键,具体语法如下:alter table student add constraint pk_id primary key (id).

其次我们说下在建表时就创建外键约束,具体语法如下:create table score(studentno int, foreign key(studentno) references student(id) ,subject varchar2(10)...),这种方法在建表时直接创建外键约束。此外还有一种就是在表建好之后,运用aletr语句,进行外键的添加:alter table score add constraint fk_no foreign key (studentno)  references student(id).

最后就是在存在主外键关系的数据表中,如果要给子表执行insert操作,前提是在父表中已经存在关联字段的值,如果不存在,执行会出错,另外一个就是在删除表时,如果子表中有记录,则要先删除子表中的数据,再删除父表中的数据。

 
 


猜你喜欢

转载自blog.csdn.net/william_zhangsun/article/details/78028446
今日推荐