加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > MsSql教程 > 正文

sqlserver数据库设计完整性与约束

发布时间:2020-12-12 14:20:48 所属栏目:MsSql教程 来源:网络整理
导读:1 use StudentManageDB 2 go 3 -- 创建主键约束 4 5 if exists ( select * from sysobjects where name = ‘ pk_StudentId ‘ ) 6 alter table Students drop constraint pk_StudentId 7 alter table Students add constraint pk_StudentId primary key (Stu
 1 use StudentManageDB
 2 go
 3 --创建主键约束
 4 
 5 if exists(select * from sysobjects where name=pk_StudentId)
 6 alter table Students drop constraint pk_StudentId
 7 alter table Students add constraint pk_StudentId primary key(StudentId)
 8 
 9 --创建唯一约束
10 if exists(select * from sysobjects where name=uq_StudentIdNo)
11 alter table Students drop constraint uq_StudentIdNo
12 alter table Students add constraint uq_StudentIdNo  unique(StudentIdNo)
13 
14 --创建检查约束
15 if exists(select * from sysobjects where name=ck_Age)
16 alter table Students drop constraint ck_Age
17 alter table Students add constraint ck_Age  check(Age between 18 and 25)
18 
19 if exists(select * from sysobjects where name=ck_PhoneNumber)
20 alter table Students drop constraint ck_PhoneNumber
21 alter table Students add constraint ck_PhoneNumber  check(len(PhoneNumber)=11)
22 
23 
24 update Students set PhoneNumber=13099012876 where StudentId=10000
25 select * from Students
26 
27 --创建默认值
28 if exists(select * from sysobjects where name=df_StudentAddress)
29 alter table Students drop constraint df_StudentAddress
30 alter table Students add constraint df_StudentAddress default(地址不详) for StudentAddress
31 
32 insert into Students (StudentName,Gender,Birthday,Age,StudentIdNo,PhoneNumber,33 StudentAddress,ClassId)
34 values(李小璐,,1989-01-12,24,120229198901121315,13099012876,default,1)
35 
36 insert into Students (StudentName,37 ClassId)
38 values(李小璐,120229198901121316,1)
39 
40 --外键约束
41 insert into StudentClass (ClassId,ClassName) values(1,软件1班)
42 if exists(select * from sysobjects where name=fk_ClassId)
43 alter table Students drop constraint fk_ClassId
44 alter table Students add constraint fk_ClassId  foreign key (ClassId) references StudentClass(ClassId)
45 
46 select * from studentClass

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读