首页 > 技术文章 > sql2008

iitb 2017-05-23 13:27 原文

1. 创建表:
create table 表名
(
列名 类型 是否为空 约束
...
)

2. 数据查询:
select

3. 数据定义:
create 、alter、 drop

4. 数据操作:
insert update delete

5. 数据控制:
grant ,revoke (授权,收回授权)

6. 修改列名: sp-rename e.g sp-rename "学生表" student

7. 查询数据表中的数据:
select * from 表名

8. 插入数据:
insert into 表名 values(要插入的数据);

9. 修改数据:
1)修改主键约束:
alter table 表名
add constraint 主键名 primary key(列名)

2)删除主键约束:
alter table 表名
drop constraint 主键名

3)添加列:
alter table 表名
add 列名 类型 是否为空

4)删除列:
alter table 表名
drop column 列名

5)修改列的宽度,是否为空,列的类型
alter table 表名
alter column 列名 类型 是否为空

6)添加唯一约束:
alter table 表名
add constraint UQ_表名_列名 unique(列名)

7)新建唯一约束:
create table m
(
a int not null unique,
b int
)
注释:unique=constraint UQ_m_a unique

8)添加check约束:
alter table 表名
add constraint CK_表名_列名 check(1.0<=表名 and 表名<=10.0)

9)添加默认值约束:
alter table 表名
add constraint DF_表名_列名 default '' for 列名
注释:''单引号中加入默认值e.g 男, 在插入数据时,写default

10)添加外键约束:
alter table 表名
add constraint FK_外表_本表 foreign key(本表列名) references 外表表名(外表列名)
默认后面会加上:on delete no action on update no action
e.g 添加级联方式外键约束:
alter table 表名
add constraint FK_外表_本表 foreign key(本表列名) references 外表表名(外表列名) on delete cascade on update cascade


主键和外键的设置:

在查询分析器中用SQL语句创建关系数据库基本表:
学生表Students(Sno,Sname, Semail,Scredit,Sroom);
教师表Teachers(Tno,Tname,Temail,Tsalary);
课程表Courses(Cno,Cname,Ccredit);
成绩表Reports(Sno,Tno,Cno, Score);
其中:Sno、Tno、Cno分别是表Students、表Teachers、表Courses的主键,具有唯一性约束,Scredit具有约束“大于等于0”;

Reports中的Sno,Tno,Cno是外键,它们共同组成Reports的主键。

create table Reports(
Sno int not null constraint FK1 foreign key references Students(Sno),
Tno int not null constraint FK2 foreign key references Teachers(Tno),
Cno int not null constraint FK3 foreign key references Courses(Cno),
Score int,
constraint PK_Reports primary key(Sno,Tno,Cno)
)

 

推荐阅读