SQL六种约束

数据库的约束


1.not null 非空约束

  • ①强制列不接受空值
  • ②例:创建表时,name varchar(6) not null,

2.unique 唯一性约束

  • ①约束唯一标识数据库表中的每条记录
  • ②unique和primary key都为数据提供了唯一性约束
  • ③primary key 拥有自动定义的Unique约束
  • ④注意:每个表中只能有一个primary key约束,但是可以有多个Unique约束
  • ⑤语法:
    1.name int unique
    2.unique(column_name)
    3.CONSTRAINT uc_PersonID UNIQUE (Id_P,LastName) 添加多个约束
    4.alter table table_name add unique(column_name) 增加表中的约束
    5.ALTER TABLE table_name DROP CONSTRAINT 主键名 删除约束

3.primary key约束

  • ①约束唯一标识数据库表中的每条记录
  • ②主键必须包含唯一的值
  • ③主键列不能为空
  • ④每个表都应该有个主键,但只能有一个主键
  • ⑤语法:
    1.StudentID int not null primary key 创建学生编号为主键
    2.primary key(Students) 创建学生编号为主键
    3.primary key(StudentID,Email) 创建学生ID和Email为联合主键
  • ⑥为已存在的列创建主键
    1.alter table table_name add primary key(column_name)
  • ⑦删除主键约束
    1.alter table table_name drop primary key
  • ⑧删除主键约束
    1.alter table table_name drop constraint 主键约束名 主键约束名可以使用sp_help查询

4.foreign key约束

  • ①一个表中的foreign key 指向另一个表的primary key
  • ②foreign key约束用于预防破坏表之间连接的动作
  • ③foreign key约束也能防止非法数据插入外键列,因为它必须是指向的那个表的值之一
  • ④语法:
    1.foreign key (column_name) references 主表名(主键列名) 创建column_name为主表名的外键
    2.column_name int foreign key references 主表名(主键列名) 创建column_name为主表名的外键
    3.alter table table_name
    add foreign key (列名) references 主表名(主键列名) 为已存在的列创建外键
    4.alter table table_name drop constraint 外键约束名 删除外键约束(SQL Server oracle)
    5.alter table table_name drop foreign key 外键约束名 删除外键约束(Mysql)

5.check 约束

  • ①check约束用于限制列中的值的范围
  • ②如果对个单个列做check约束,那么该列只可以输入特定数值
  • ③如果一个表定义check约束,那么此约束会在特定的列对值进行限制
  • ④语法:
    1.StudentID int not null check (StudentID>0) 限制StudentID输入的值要大于0 (SQL Server oracle)
    2.StudentID int not null, 限制StudentID输入的值要大于0 (Mysql)
    check (StudentID>0)
    3.sex varchar(2) not null check(sex=‘男’ or sex=‘女’) 限制sex的性别只能是男或者女
    4.alter table table_name add check(列名>0) 向已有的列加入check约束
    5.alter table table_name drop constraint check约束名 删除约束 约束名可以用 sp_help table_name查看

6.default约束

  • ①default约束用于向列中插入默认值
  • ②如果没有规定其他的值,那么会将默认值添加到所有的新记录中
  • ③语法:
    1.name varchar(10) default ‘张三’ name默认插入张三的名字
    2.systime date default gatedate() 插入时间的默认值 getetime()函数为时间的默认值
    3.alter table table_name add 列名 set default ‘数值’ 向已有列名中插入默认值
    4.alter table table_name drop constraint 约束名 删除默认约束
发布了104 篇原创文章 · 获赞 60 · 访问量 5842

猜你喜欢

转载自blog.csdn.net/Q_1849805767/article/details/103731914