为数据库添多个表加约束

为数据库添多个表加约束,第1张

创建SQL的主键和外键约束的方法:--在创建表时就可以对字段加上约束:
create table Buy(buyo int PRIMARY KEY, username varchar(20) FOREIGN KEY REFERENCES Users(username) NOT NULL, goodsno char(5) FOREIGN KEY REFERENCES Goods(goodsno) NOT NULL, quantity int CHECK(quantity >0 ) , buydate DATETIME)

alter table s add constraint CK_sex CHECK(sex='m'&&age<23) or CHECK(sex='f'&&age<23)

默认值 不能成为 约束 条件的!它只是在你没有给这个字段输入新的数据之前 默认一个数值(是可以后续任意修改的)……
这个 需要在 表的 设计视图上 对应的 字段属性里 进行设置……
设计视图中 字段列表里 选择 birthday 字段 然后 在下方的常规属性 默认值 里边填写#1999-9-9#……

alter table a add CONSTRAINT [IX_a] UNIQUE
(
[a1] ,
[vv1]
)
在表a的列a1,vv1上添加UNIQUE 约束,约束名为IX_a

给这个表添加一个触发器,触发器类型为插入和更新事务的(inserted|updated),
Create Trigger 触发器名
On 表
For {insert,update}
As
Begin
SQL语句块
End
SQL语句块的基本思想是:
用charindex()函数检查字段里是否包含单引号('),若包含,则事务回滚(rollback),并提示(print……);若不包含,则提交事务(commit)。
比如insert事务:
If(select charindex("'",字段) From 表,inserted
Where 表字段编号=inserted字段编号) > 0
Begin
Rollback
Print “要显示的提示”
End
Else
commit
只是粗略写了一下,完整结构你自己丰富一下吧

sql server中建立外键约束有3中方式: 1Enterprise Manager中,Tables,Design Table,设置Table的properties, 可以建立constraint, reference key; 2Enterprise Manager中,Diagrams, new Diagrams,建立两个表的关系。 3直接用transact sql语句。 下面讲解一下用SQL添加外键约束的实例: 一个SQL创建外键的例子: ///建库,名为student_info/ create database student_info ///使用student_info/ use student_info go ///建student表,其中s_id为主键/ create table student ( s_id int identity(1,1) primary key, s_name varchar(20) not null, s_age int ) go ///建test表,其中test_no为主键/ create table test ( test_no int identity(1,1) primary key, test_name varchar(30), nax_marks int not null default(0), min_marks int not null default(0) ) go ///建marks表,其中s_id和test_no为外建,分别映射student表中的s_id和test表中的test_no/ create table marks ( s_id int not null, test_no int not null, marks int not null default(0), primary key(s_id,test_no), foreign key(s_id) references student(s_id), foreign key(test_no) references test(test_no) ) go

参考资料:

>对着表定义窗口右键选择CHECK 约束 在 点添加 在“表达式”一行中填写就行了。
1 len([列名])=10
2 [列名] like '00%'
3[列名] like '__[0-9][0-9]%'
4[列名] like '____[_]%'
5[列名] like '_____[a-z,A-Z][a-z,A-Z][a-z,A-Z]%'
这样式不是很简单啊 直接 *** 作工具就行了。这应该没超出你所学吧 都是 sql的运算符

增加check约束条件即可。sql中表名称为中文时增加check约束条件即可用命令给表添加约束。表(TABLE)是数据库中用来存储数据的对象,是有结构的 数据的集合,是整个数据库系统的基础。


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/yw/13141966.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-06-11
下一篇 2023-06-11

发表评论

登录后才能评论

评论列表(0条)

保存