添加约束
--添加主键约束:
alter table 表名add constraint 约束名 primary key(要设为主键的列名)
--添加唯一约束:
alter table 表名add constraint 约束名 unique(stuName)
--添加检查约束:
alter table 表名add constraint 约束名 check(条件,如:stuSex='男' or stuSex='女')
--添加默认约束:
alter table 表名add constraint 约束名 default(要设置的默认值) for stuSex
--添加外键约束:
alter table 表名add constraint 约束名 foreign key(本表的列名) references 主键表名(列名)
一个简单的例子 包括创建数据库 外键 约束 check 改类型
create database ytf
use ytf
go
/*建S表*/
create table S(Sno char(10) primary key,Sname char(10),Status int,City char(10))
/*建P表*/
create table P(Pno char(10) primary key,Pname char(10),Color int,Weight int)
/*建J表*/
create table J(Jno char(10) primary key,Jname char(10),City char(10))
/*建J表 外键的建立*/
create table JPS(Pno char(10),Jno char(10),Sno char(10),QTY char(10),
primary key(Pno,Jno,Sno),
Foreign Key (Pno) references P(Pno),
Foreign Key (Jno) references J(Jno),
Foreign Key (Sno) references S(Sno))
/*为SPJ表增加一供应日期列,列名为SUPDATE,日期型*/
alter table JPS add SupDate date
/*为S、P、J表的SNAME、PNAME、JNAME列定义UNIQUE约束;约束名分别命名为UQ_SNAME, UQ_PNAME,UQ_JNAME;*/
alter table S add constraint UQ_SNAME unique(Sname)
alter table P add constraint UQ_PNAME unique(Pname)
alter table J add constraint UQ_JNAME unique(Jname)
/*实现DATE属性的Check(检查)约束: SUPDATE<getdate()*/
alter table JPS add constraint cons_date_chk check(SupDate<getdate())
/*删除P表PNAME列的唯一性约束*/
alter table P drop constraint UQ_PNAME
/*将P表中PNAME列的数据类型改为可变字符串型*/
alter table P alter column Pname varchar(50)
/*用SQL语言在SPJ表上建立一个唯一性索引。*/
create unique index ytf on JPS (QTY)