DDL 数据定义语言
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 ;
建表语句约束
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约束有多个空值的。
子查询创建表
create table h_emp
as
select * from scott.emp where deptno;
注:只要表结构
例:create table h_emp
as
select * from scott.emp where 1=2 ;
2. 修改
语法:ALTER TABLE 表名
1) 添加一个新列
alter table 表名 add 列名 类型(长度)[约束&默认值];
例:alter table student add City varchar(255) not null;
2)修改现有的列定义
alter table student modify City varchar(300) unique not null;
3)删除一列
alter table student drop column City ;
4) 新的列定义默认值
alter table student modify city default ‘北京’;
5)重命名列
alter table 表名 rename column 旧列名 to 新列名;
6)将表更改为只读状态
ALTER TABLE 表名 READ ONLY;
ALTER TABLE 表名 READ WRITE;(改回可编辑模式)
3.删除
语法:drop table 表名;
4.备注
----表名描述
comment on table testemp is ‘测试专用表’;
----字段备注
comment on column testemp.deptno is ‘部门编码’;
comment on column testemp.ename is ‘人名’;
comment on column testemp.sal is ‘工资’;