SQLServer创建约束

--创建数据库
create database students
on primary
(
    name=stu_data,
    filename='f:\SQL\stu_data.mdf',
    size=1,
    maxsize=10,
    filegrowth=1
)
log on
(
    name=stu_log,
    filename='f:\SQL\stu_log.ldf',
    size=1,
    maxsize=10,
    filegrowth=1
)
--删除数据库
drop database students
--使用数据库
use students
--删除表
drop table score
drop table student
drop table class
--自定义类型
Exec sp_addtype age,int ,'not null'
--定义表时第一种方法创建主键外健

create table student
(
    fCode char(10) identity(1,2) constraint PK_fCode1 primary key,
    fName varchar(15) not null constraint DF_fName default 'sss',
    fClass varchar(5) not null default '',
    fSex varchar(2)  not null default ''constraint CK_fSex check (fSex in('男 ','女')),
    fAge age
)
create table score
(
    fId char(10) constraint FK_fId foreign key (fId)references student,
    fSubject varchar(10) not null default '',
    fScore int not null default 0 constraint CK_fScore check(fScore>=0 and fScore<=100)
)
--定义表时第二种方法创建主键外键
create table class
(
    fClassId int not null,
    fTeacherName varchar(10) not null,
    fYear varchar(4)not null unique,
    constraint PK_fClassId primary key (fClassId),
    constraint FK_fClassId foreign key (fClassId) references student
    
)
--实例表
drop table A
create table A
(
    fCode int not null,
    fClassId varchar(5)not null,
    fName varchar(4)not null,
    fSex varchar(2)not null,
    
)
--添加唯一性约束
alter table A
add constraint UQ_fClassId_A unique(fClassId)
--添加主键,默认值,检查,外键约束
alter table A
add constraint  PK_fCode_A primary key(fCode)

alter table A
add constraint DF_fName_A default '' for fName

alter table A
add constraint CK_fSex_A check(fsex in('男','女'))

alter table A
add constraint FK_fCode_A foreign key(fCode) references student
--删除约束
alter table A
drop constraint DF_fName_A
--增加列
alter table A
add fAge int null
--删除列
alter table A
drop column fAge

/*注意
    1、主键表中主键列的类型和长度必须和外键表中列的类型和长度相同
    2、外键表中列的取值只能是主键表中主键列的子集*/
    
    
/*
--新增所有列数据
insert into student values('李鸿','0201','女',23)
insert into student values('John','0201','男',23)
insert into score values(1,'英语',90)
insert into class values(1,'逐月','2002')
insert into score values(2,'英语',102)
--新增数据部分列
insert into student(fName,fSex) values('桐港','男')

select * from student
select * from score
select * from class*/

posted @ 2014-03-21 22:51  zhangyongjian  阅读(519)  评论(0编辑  收藏  举报