1.建表语句
create table 表名
( 列1 数据类型(长度)
,列2 数据类型(长度)
,列3 数据类型(长度)
…
);
例:create table zhiyu30
(
sno number(4)
,sname varchar2(10)
,sage number(2)
,sdate date default sysdate
);
select rowid ,a.* from student a ;
2.建表语句约束
create table 表名
( 列1 数据类型(长度)not null -------不为空
,列2 数据类型(长度)unique----------唯一
,列3 数据类型(长度)–primary key--------主键
CONSTRAINT emp_id_pk PRIMARY KEY
,列4 数据类型(长度)foreign key references dept(dept_id) -----外键
,列5 数据类型(长度)check (sage < 100)---- 检查
…
,
);
select * from scott.emp
注:
1)每张表只能有一个主键,联合主键只能建表级约束
2)删除约束不会影响表结构及表内的数据
3)约束的名字是否可以相同
例:create table sc1(
sno varchar2(10) ,
cno varchar2(10) ,
score number(5,2),
constraint pk_sc1 primary key (sno,cno),
constraint pk_sc1 primary key (sno,cno)
);
例:–员工表
create table emp1
(
emp_id int constraint pk_emp_id primary key,–设置主键并命名
emp_name varchar2(20) not null,–名字不能为空
emp_sex char(1),
–设置外键,该外键来自于dept表(主键表)
dept_id int ,
constraint fk_dept_id foreign key(dept_id) references dept(dept_id)
);
create table student2
(
stu_id int primary key,
stu_sal int check (stu_sal >= 1000 and stu_sal <= 8000),–check约束
stu_sex char(3) default ‘男’, --()可以省略,在数据库中字符串必须用’'括起来
stu_name varchar2(200) unique–unique约束
);
除了SQL SERVER 以外的大型数据库都是允许 UNIQUE约束有多个空值的。
3.子查询创建表
create table h_emp
as
select * from scott.emp where deptno;
注:只要表结构
例:create table h_emp
as
select * from scott.emp where 1=2 ;