1 创建数据库
- 语句
create datatbase
用于创建数据库。 - 语法
create datatbase
数据库名称 - 示例
create database demo
2 建表
- 语句
create table
语句用于创建数据库中的表。 - 语法
create table
表名称
(
列名称1 数据类型,
列名称2 数据类型,
列名称3 数据类型,
…
) - 示例
/* Table1: Student 学生表 */
create table Student (
sno int primary key, --学号
sname nvarchar(32) not null, --姓名
sage int not null, --年龄
ssex nvarchar(8) --性别
)
3 删表
- 语句
drop table
语句用于删除表(表的结构、属性以及索引也会被删除) - 语法
drop table
表名称 - 示例
drop table Student
4 插入一条记录
- 语句
insert into
语句用于向表格中插入新的行。 - 语法
insert into
表名称values
(
值1, 值2,…)
- 示例
--插入一条
insert into Student VALUES (1001, '张三', 20, '男')
--插入多条
insert into Student VALUES
(1002, '李四', 21, '男'),
(1003, '王五', 15, '女'),
(1004, '刘六', 18, '女')
结果
5 修改一条记录
- 语句
update
语句用于修改表中的数据。 - 语法
update
表名称set
列名称=
新值WHERE
列名称=
某值 - 示例
update Student set sage = '50' WHERE sname = '李四'
结果
6 删除一条记录
- 语句
delete
语句用于删除表中的行。 - 语法
delete from
表名称where
列名称=
值 - 示例
delete from Student where sname = '李四'
结果
7 添加、修改、删除一列
-
语句
alter table
语句用于在已有的表中添加、修改或删除列。 -
语法
如需在表中添加列,请使用下列语法:
alter table
表名add
列名 数据类型如需在表中修改列,请使用下列语法:
exec sp_rename
‘表名.[字段旧名]’, ‘字段新名’, 'column'
;要删除表中的列,请使用下列语法:
alter table
表名drop column
列名 -
示例
--添加列
alter table Student add scard int
--修改列
exec sp_rename 'Student.[sage]', 'sages' , 'column'
--删除列
alter table Student drop column scard
8 备份或复制表数据
-
语句
select into
语句可用于创建表的备份复件,从一个表中选取数据,然后把数据插入另一个表中。 -
语法
您可以把所有的列插入新表:
select * into
新表名from
旧表名或者只把希望的列插入新表:
select 列名1,列名2 into 新表名 from 旧表名 -
示例
--把所有列插入新表
select * into Student_backup from Student
--把希望的列插入新表
select sno,sname into Student_backup2 from Student
--按条件插入数据到新表:带有Where子句
--所有列
select * into Student_backup3 from Student where sname = '张三'
--指定列
select sno,sname into Student_backup4 from Student where sname = '张三'
8.1 Select Into 多表查询生成新的表
- 思路
主要是利用多表联合查询(比如内联接--inner join
)方式查找到新的数据,然后将查找的数据按照所有列或指定列插入到新的表中 - 示例
(1)创建两张表:学生表stu_Student
和 班级表stu_Class
/* Table1: stu_Student 学生表 */
create table stu_Student (
sno int primary key, --学号
sname nvarchar(32) not null, --姓名
sage int not null, --年龄
ssex nvarchar(8), --性别
scno int --班级号
)
/* Table1: stu_Class 班级表 */
create table stu_Class (
cno int primary key, --班级号码
cname nvarchar(32) not null, --班级名称
cposition nvarchar(32) not null --所在位置
)
注释:我们通过两表中的字段:`scno`和`cno`进行关联
(2)给两张表插入数据
--插入多条
insert into stu_Student VALUES
(1002, '李四', 21, '男', 10),
(1003, '王五', 15, '女', 11),
(1004, '刘六', 18, '女', 11)
--插入多条
insert into stu_Class VALUES
(10, '实验班','教学楼1楼'),
(11, '平行班', '教学楼2楼')
(3)多表查询联合插入数据到新表
--多表查询插入数据到新表
--所有列
select * into newtable from stu_Student s inner join stu_Class c on s.scno = c.cno
--指定列
select s.*,c.cname into newtable2 from stu_Student s inner join stu_Class c on s.scno = c.cno
结果
代码说明
(1)stu_Student s
和 stu_Class c
中的s和c是对表申明变量,方便简写使用;
(2)第二句中的s.*
是指stu_Student
的所有字段