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的所有字段
本文详细介绍了数据库的基本操作,包括创建数据库、建表、删表、记录的增删改查、列的添加修改删除以及数据的备份复制等核心内容,适合初学者快速掌握数据库管理技巧。
3032

被折叠的 条评论
为什么被折叠?



