sql2005数据完整性之约束和规则

--数据的完整性

六种约束:not null 、checkuniqueprimary keyforeign keydefault

--创建唯一约束

--这是删除唯一约束

alter table xibu 

drop constraint weiyi

--这是建立唯一约束

alter table xibu 

add constraint weiyi

unique nonclustered (xbName)

alter table xibu

alter column  asd char(8)

--这是check约束

insert xs values('010101000017','克群','','1989-2-9','2010-9-1','0101011','04','0402')

select * from xs

if exists(ck_xs)

alter table xs 

drop constraint CK_xs

alter table xs 

add constraint aaa

check(sex = '')

--withnocheck对你以前插入的数据不进行检查

alter table xs with nocheck add 

constraint CK_sex check(sex ='' or sex='')

exec sp_help xs--这是查看表结构

--这是default约束

alter table bj drop constraint DF_bj_bz

alter table bj add constraint DF_bj_bz default '我爱你' for bz;

create table test

(

id int not null primary key,

name varchar(10) not null 

)

drop table test

alter table test 

drop constraint aaa

alter table test with nocheck

add constraint aaa default '我真的' for name

exec sp_help test

insert into test values(2,default);

select * from test

规则

/*数据的完整性*/
--规则的创建 
create rule check_rule
as
@a = '男' or @a = '女'
--将规则绑定到数据库表的字段上
exec sp_bindrule 'check_rule', 'test.name'

insert into test values(1, '男');

select * from test

--注意:规则可以用到多个表上
select * into new_table from test
select * from new_table

exec sp_bindrule 'check_rule', 'new_table.name'
insert into new_table values(1, 'asd');
--删除绑定到表中某个字段上的规则
exec sp_unbindrule 'new_table.name'
exec sp_unbindrule 'test.name'
--删除规则
drop rule check_rule

--default规则的一些应用
--创建默认值
create default ch_default
as '曹欢'
--将默认值绑定到数据库表的某个字段
exec sp_bindefault ch_default,'test.name'
insert into test values(13,default);

select * from test
--删除绑定到表字段上的default约束
exec sp_unbindefault 'test.name'
--删除default的默认值
drop default ch_default

--这是对这节的练习
create table test1 (
 id int identity(1,1)  primary key ,
 sex varchar(4) not null,
 name varchar(12)
)

select * from test1
exec sp_help test1
 --创建规则
create rule check_rule
as
@sex = '男' or @sex = '女'
--把规则应运到
exec sp_bindrule 'check_rule','test1.sex'

exec sp_unbindrule 'test1.sex'
drop rule check_rule

insert into test1 values('男','asd')
select * from test1

create default default_rule
as '曹欢'

exec sp_bindefault 'default_rule','test1.name'
exec sp_unbindefault  'test1.name'
drop default default_rule
insert into test1 values('男',default)

select * from test1

 

 

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值