硬是一拖再拖,直到了今天才更。
--表中列的类型
-- int 整型-- char(10) 字符串 固定长度 查询速度快,浪费空间 如身份证号 手机号码 学号
-- varchar(10) 字符串 可变长度 姓名 地址
-- 不带n的:字符或者数字占一个字节,汉字为两个字节
-- 带n的:双字节存储,字母或者数字、汉字两个字节
-- nchar(10)
-- nvarchar(10)
-- 存图片时,图片上传到服务器上,在数据库只存路径
-- 建表语句
use studentmanager
if exists(select *from sysobjects where name='table_student')
drop table table_student
create table table_student
(
-- 字段名 字段的特征
id int identity(1,1) primary key, --在创建表时就设定为主键列与自增列
stu_number char(12) not null, --不允许为空
stu_name varchar(20) not null,
stu_age int,
birthday datetime,
class_id int references table_class(class_id) --外键
)
create table table_class
(
class_id int identity(1,1) primary key,
class_name varchar(20) not null,
create_time datetime
)
-- 约束的目的 确保表中数据的完整性
-- 行完整性(实体完整性):主键约束与唯一约束
-- 列完整性(域完整性) :检查约束、默认约束与非空约束
-- 参照完整性 :外键约束
use studentmanager
drop table table_class
drop table table_student
if exists(select *from sysobjects where name='table_student')
drop table table_student
create table table_student
(
-- 字段名 字段的特征
id int not null,
stu_number char(12),
stu_name varchar(20) ,
stu_age int,
birthday datetime,
class_id int
)
create table table_class
(
class_id int not null,
class_name varchar(20),
create_time datetime
)
-- 追加约束
-- 主键约束(向哪个表 加什么约束 加在哪个列上面) 非空唯一
alter table table_student
add constraint PK_id primary key(id)
alter table table_class
add constraint PK_class_id primary key(class_id)
-- 唯一约束 可以为空 但唯一 只允许一个为空
alter table table_student
add constraint UK_stu_number unique(stu_number)
--检查约束
alter table table_student
add constraint CK_stu_age check(stu_age>0 and stu_age<150)
--默认约束
alter table table_class
add constraint DF_create_time default(getdate()) for create_time
--外键约束
alter table table_student
add constraint FK_class_id foreign key (class_id) references table_class(class_id)
--建表时直接加约束
--create table table_student
--(
-- id int identity(1,1) primary key,
-- stu_number char(12) unique not null,
-- stu_name varchar(20) not null,
-- stu_age int check(stu_age>0 and stu_age<150),
-- birthday datetime default(getdate()),
-- class_id int references table_class(class_id)
-- )
--删除约束
alter table table_student
drop constraint UK_stu_number
--------携着一股什么也不服的劲在活着