约束问题@!

qiuming0306 2008-03-20 03:54:06
如何给一个表的字段添加自定义约束,比如只限定这个字段只能是固定的几个数字,添加约束后有何优缺点!如果用Default(函数)的形式检查是不是很好!呵呵,查了一些资料,都只是介绍约束如何使用!至于原理效率什么的没找到啥!CHECK_CONSTRAINTS特别是这个资料特别少馁!
...全文
82 6 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
qiuming0306 2008-03-20
  • 打赏
  • 举报
回复
老乌龟有没有约束的原理和效率的说明,建约束之后对数据操作有什么影响!
dawugui 2008-03-20
  • 打赏
  • 举报
回复
alter table tb add constraint ck1_index check(col in ('MM','GG'))
alter table tb add constraint ck2_index check(col in (1,2))
wzy_love_sly 2008-03-20
  • 打赏
  • 举报
回复

--我整理的一点
--drop table index_tb
create table index_tb(id int constraint ck_id default 0,name varchar(20),xb varchar(2))
--查看表
exec sp_helpindex orders--索引
exec sp_helpconstraint index_tb --约束
exec sp_fkeys 'dbo.Person'--外键
--键不唯一,非聚集索引
create index id_index on index_tb(id)
--删除索引
drop index index_tb.id_index
--键聚集索引
create clustered index id_index on index_tb(id)
--删除索引
drop index index_tb.id_index
--创建check约束
alter table index_tb add constraint ck_index CHECK (name like '[0-9][0-9][0-9][0-9][0-9]')
alter table index_tb add constraint ck2_index check(xb in ('MM','GG'))
--删除check约束
alter table index_tb drop constraint ck2_index
--禁止表约束
alter table index_tb nocheck constraint ck_index
--恢复表约束
alter table index_tb check constraint ck_index
--禁止和恢复所有check-all关键字
select 'alter table '+name+' nocheck or check constraint all' from sysobjects where type='U'
--添加新默认值和约束
ALTER TABLE index_tb ADD CONSTRAINT de_name DEFAULT ('11111') FOR name
--删除表约束
alter table index_tb drop constraint de_name
-- 字段 UNIQUE NOT NULL = PRIMARY KEY 差不多
--创建unique
alter table index_tb add constraint uniqueindex unique(id)
--删除unique
alter table index_tb drop constraint uniqueindex

insert into index_tb(name,xb) select '12345','mm'

select * from index_tb

delete index_tb


liangCK 2008-03-20
  • 打赏
  • 举报
回复
--创建check约束
alter table index_tb add constraint ck_index CHECK (name like '[0-9][0-9][0-9][0-9][0-9]')
alter table index_tb add constraint ck2_index check(xb in ('MM','GG'))
--删除check约束
alter table index_tb drop constraint ck2_index
--禁止表约束
alter table index_tb nocheck constraint ck_index
--恢复表约束
alter table index_tb check constraint ck_index
--禁止和恢复所有check-all关键字
select 'alter table '+name+' nocheck or check constraint all' from sysobjects where type='U'
--添加新默认值和约束
ALTER TABLE index_tb ADD CONSTRAINT de_name DEFAULT ('11111') FOR name
--删除表约束
alter table index_tb drop constraint de_name
-- 字段 UNIQUE NOT NULL = PRIMARY KEY 差不多
liangCK 2008-03-20
  • 打赏
  • 举报
回复
alter table tb
add constraint chk_col check (col like '[1-9][5-9]')
tcxx2008 2008-03-20
  • 打赏
  • 举报
回复
沙发

22,300

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server 疑难问题
社区管理员
  • 疑难问题社区
  • 尘觉
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧