SQL基础之常用数据类型,约束
/*常用数据类型*/->数字类型:int,tinyint
->时间类型:datatime 格式:”yyyy-MM-dd hh:mm:ss.sss”
->二进制数据类型 image (存储图片)
-> bit 类型 1 0 ‘true’ ‘false’
->字符串类型:
Char,nchar,varchar,nvarchar
//可以存储大量的字符串
varchar(max)
nvarchar(max)
//不建议使用下面这两个,因为被淘汰了
text
ntext
Varchar 与char的区别
1可变长度 varchar(节省空间,不过效率相对来说慢一点)
2 固定长度 char (比较浪费空间)
Nchar(10),char(10)的区别
Char 存储的是字节个数
Nchar 存储的是字符个数,用来存储中文
/*约束*/
-- 保护数据完整性的机制:让存储的数据有意义的条件
/*
分类
1.主键约束
2.唯一约束
3.检车约束
4.默认约束
5.非空约束
6.主外键约束
*/
-- 基本语法
/*
alter table 架构.表名
add constraint 约束名 约束类
*/
1->添加检查约束
1
2
3
4
alter table Mydounaifen.TlStudent
add constraint CK_TlStudent_stuSex
check(stuSex='男'or stuSex='女');
--其他约束类似
2->删除多个约束,约束名用,隔开
1
2
3
4
alter table Employees
drop constraint
DF_Employees_EmpGender,
CK_Employees_EmpAge
3->增加多个约束
1
2
3
4
5
6
7
8
9
10
11
/*添加非空约束
为年龄与性别添加检查约束
为邮箱添加唯一约束
*/
alter table Student
add constraint ck_Student_stuAge
check(stuAge>0 and stuAge<30),
constraint ck_Student_stuSex
check( stuSex='男'or stuSex='女'),
constraint uq_Student_stuEmail
unique(stuEmail);
4->增加一列
1
2
alter table Mydounaifen.TlStudent
add email varchar(20) null;
5->修改某个列数据类型
1
2
alter table Mydounaifen.TlStudent
alter column email nvarchar(20) null;
6->删除一列
1
2
alter table Mydounaifen.TlStudent
drop column email;
示例代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
create table tblCourseT_SQL2
(
cId int identity(1,1) not null
, cName nvarchar(10) not null
, cDesc nvarchar(100) null -- description
);
alter table tblCourseT_SQL2
add constraint PK_tblCourseT_SQL2_cId primary key(cId);
-- 学生
create table tblStudentT_SQL2
(
stuId int identity(1,1) not null
, stuName nvarchar(10) not null
, cId int null -- 外键stuTocId
);
--创建外键约束主键表中必须有个主键
alter tabletblStudentT_SQL2
add constraint
foreign key(cId) references tblCourseT_SQL2(cId);
/*
补充说明
主外键表中,关联主键表的字段必须是主键和唯一键
*/
页:
[1]