数据库笔记二:表的基本操作

--创建一张表 Student
create table Student
(
ID int  unique not null,--unique设置ID列唯一值约束,not null 为此列添加非空约束
                        --只能在添加列时为列添加非空约束
Name char(10),--10表示这一列的数据的长度,没有则默认为1
Age int ,
Sex bit,
)
--删除一张表
drop table Student
--为表添加主键,不能为 可为空的列添加主键约束
alter table Student
add constraint pk3 primary key ( ID) 
--为列添加默认值约束,def为约束的名称,方便以后使用
alter table Student 
add constraint def default 1 for Sex
--为列添加检查约束
alter table Student
add constraint ck3 check (Age>10 and Age<30)
--为列添加外键约束,外键约束用于表和表之间的关系
  --首先创建一张成绩表,让成绩表中的学号和学生表中的学号约束
  --为学生表添加学号列Num并设置此列的值唯一
  alter table Student
   add  Num int unique
   --创建成绩表
  create table Score
   (
   SNum int,
   Math int,
   Chinese int
   )
   --为Num列创建外键约束,如果Score表中的一个字段必须在Student表中存在,
   --则Score表为从表,Student表为主表,改字段称为表Student的外键。
  --下面创建约束,创建约束的键必须是唯一值的
  alter table Score
   add constraint studentid foreign key(SNum) references Student(Num) 
--删除列,删除列时必须删除该列所有的约束,否则不能删除
alter table Student
drop column Sex
--删除约束,删除约束时必须有约束名称,ck3为约束名称
alter table Score
drop constraint studentid

posted @ 2011-09-06 16:55  再见雪天  阅读(295)  评论(0编辑  收藏  举报