创建数据表
表是数据库中最基本的数据对象,用于存放数据库中的数据。
创建表:table1
主键:primary key ;默认值:default;自动增长:identity(p,s);check:检查;not null:非空
创建表table1:
use tt3
go
create table table1
(
id int identity(1,1), --自增
学号 char(6) not null primary key , --主键
姓名 varchar(20) not null, --非空
性别 bit default 1, --默认值
出生日期 date null, --可以为空
手机号码 varchar(20) unique, --唯一约束
成绩 float check(成绩=null or 成绩 > 0) --检查约束
);
创建表table2:
use tt3
go
create table table2
(
id int identity(1,1),
学号 char(6) not null ,
姓名 varchar(10) not null,
性别 bit default 1,
出生日期 date null,
手机号码 varchar(20) unique,
成绩 float null,
primary key (学号),
constraint check_成绩 check (成绩 = null or 成绩 > 0)
-- constraint约束;unique:唯一;default:默认;identity:自增
)
go
向创建的新表table1添加数据:
--向创建的表插入数据:
insert into table1
(学号,姓名,性别,出生日期,手机号码,成绩)
values('110101','赵中耀',1,'1993-8-11','12345455533',77.5),
('110102','赵中光',1,'1995-8-11','12345455544',null),
('110103','赵中祥',1,'1997-8-11','12345455555',60),
('110104','赵中辉',1,'1991-8-11','12345456634',null);
/*
id列为自增列可以不用添加;
数据类型为定长字符型和变长字符型的用引号括起来;
日期或时间类型也要使用引号;
唯一约束的列(手机号码),注意值不要重复;
主键列(学号)的值也不能重复;
默认约束列(性别),如果不填则使用默认值;
检查约束(成绩)列,可以为空或大于0.
*/
创建外键约束:foreign key
use tt2
go
create table table3
(
id int identity(1,1),
学号 char(6) not null ,
姓名 varchar(10) not null,
性别 bit default 1,
出生日期 date null,
手机号码 varchar(20) unique,
成绩 float null,
primary key (学号),
constraint check_成绩 check (成绩 = null or 成绩 > 0)
)
go
create table table4
(
学号 char(6) not null primary key foreign key references table3(学号),
课程号 int not null,
课程名 varchar(30) not null
)
go
向新建的表添加数据:
--向新建的俩数据表添加数据:
insert into table3
(学号,姓名,性别,出生日期,手机号码,成绩)
values('110101','赵中耀',1,'1993-8-11','12345455533',77.5),
('110102','赵中光',1,'1995-8-11','12345455544',null),
('110103','赵中祥',1,'1997-8-11','12345455555',60),
('110104','赵中辉',1,'1991-8-11','12345456634',null);
go
--先向 table3 添加数据,因为它是被参考表
insert into table4
(学号,课程号,课程名)
values('110101',101,'计算机基础'),
('110102',102,'C语言');
--删除数据时先删除非参考表 table4 的数据
修改数据表结构:ALTER TABLE
修改语句,一次只能包含 ALTER COLUMN、ADD、DROP子句中的一条。
增加数据表列:
use tt3
go
alter table table2
add 备注 text; --增加列,备注,大文本类型。
select * from table2;
修改已有数据列:
alter table table2
alter column 备注 varchar(50);
--修改-列-列名-数据类型
删除已有数据列:
--删除已有数据列:
alter table table2
drop column 备注2;
select * from table2;
删除列约束:
alter table table2
drop constraint check_成绩;
--check_成绩,为创建此约束时的约束名称。
修改表名称:rename
sp_rename table2,tb2;
查看表结构信息:
--查看已创建的表结构的信息:
sp_columns tb2;
--查看已经创建的表的结构:
sp_help tb2;