SQL语句对于约束的增加及修改

SQL语句对于约束的增加及修改

使用SQL语句在初次建立数据表时,同时增加约束的方法非常简单:
create table 表名
(列名 列的属性 约束名
     [,...n] )即可,可建立的约束包括primary key 、foreign key、null/not null、check、default等
例如create table student
( stu_no char(6) primary key,
    stu_name char(10) not null,
    stu_sex char(2) check(stu_sex='男' or stu_sex='女'),       /*约束此列的值只能输入“男”或“女”值*/
    stu_nation char(10) default '汉族',
     )
create table grade
( stu_no char(6) foreign key (stu_no) references student(stu_no),      /*此为定义外键约束*/
    subject_no int,
    grade decimal(4,1) check(grade>=0 or grade <=100)                  /*约束成绩取值范围在0-100分之间*/

但是若建立好数据表之后,想要再往列增加约束或修改约束,则格式根据约束的不同各有不同:
use xscj
go
create table abc
(s_no char(10),
s_name char(10),
s_sex char(2),
    s_nation char(16)
)                  /*以上为建立一个没有任何约束的新数据表*/                     
go
alter table abc
alter column s_no char(10) not null             
go
alter table abc
add    primary key (s_no)           /* 以上为给表的s_no列加上primary key 约束*/
go
alter table abc
add check(s_sex='男'or s_sex='女')      /*给x_sex列加check约束*/
go
alter table abc
add default '汉族'    for    s_nation         /*加default约束时格式和其他的有所不同*/
go
但如果是建立表时已经给列建立了某种约束,需要修改其约束的话,则需要先删除掉原有约束,然后再增加新约束,至于删除约束的命令格式为:alter table 表名 drop constraint 约束名
此处的约束名由于建立约束时给省略了,所以需通过“sp_helpconstraint 表名”命令查看到列上对应的constraint_name(即约束名)

总结!!!

create table test /*创建test表*/

(  test_no char(6) primary key,  /*新增字段test_no 并设置为主键*/
    test_name char(10) not null, /*创建字段test_name 并设置不能空*/
    test_sex char(2) check(test_sex='男' or test_sex='女'),       /*约束此列的值只能输入“男”或“女”值 感觉有点像 vb 哈哈*/
    test_nation char(10) default '汉族', /*创建字段test_nation 并设置默认值为汉族*/
)

另外:再约束中 也可以有 and 这个连接字。
如 check(test_age>0 and test_age<=150) #年龄再0到150之间
当然还可以用 in 这个
如 check(test_sex in ('男','女','中性')) #性别是 男 女 或中性

附上:
删除约束
alter table 表名 drop constraint 约束名
增加约束
alter table abc
add check(test_sex='男'or test_sex='女')      /*给test_sex列加check约束*/

  • 5
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值