您的位置:首页 > 数据库

自学--数据库笔记--第七篇--SQL sever2008更新数据

2016-12-05 15:25 337 查看

数据库笔记—7—SQL sever2008更新数据

所有使用的都为已制作好的表

1.

插入数据 两种语句格式

insert…values语句

--1.向depart表中插入一行数据('5','计划部','008','2206')
insert into depart
values('5','计划部','008','2206')


--向worker表中插入一行数据,职工号:010,职工名:李飞龙,生日:1967-04-01,部门号:4
insert into worker(wid,wname,wbirthdate,depid)  --指定字段
values('010','李飞龙','1967-04-01','4')


--向salary表中插入一行数据,职工号:010,totalsalary:2800
insert into salary(wid,totalsalary) --错误的,有两个主键,,需要全部不为空
values('010',2800) --数字类型不加引号

insert into salary(wid,sdate,totalsalary)
values('010','2011-01-04',2800) --数字类型不加引号


–insert…select语句 从某张张表中查询的数据,放到另外一张表中

--创建一个新表worker_f,然后将worker表中所有女职工的职工号,职工名,出生日期这三个字段的信息插入进入
create table worker_f
(
wid char(3) primary key,
wname varchar(10) not null,
wbirthdate date
)

insert into worker_f
select wid,wname,wbirthdate
from worker
where wsex='女'


修改数据 update

--修改worker表中的数据,将姓名为‘李飞龙’的职工的性别修改为‘男’  基于单表
update worker
set wsex='男'
where wname='李飞龙'
--将1975年以前出生的职工2011年1月份的totalsalary增加500元,actualsalary增加400元 基于多表

--利用多表连接查询
update salary
set totalsalary=totalsalary+500,actualsalary=actualsalary+400
from worker inner join salary on worker.wid=salary.wid
where YEAR(wbirthdate)<1975 and YEAR(sdate)=2011 and MONTH(sdate)=1

--利用子查询
update salary
set totalsalary=totalsalary+500,actualsalary=actualsalary+400
where YEAR(sdate)=2011 and MONTH(sdate)=1 and wid in
(
select wid
from worker
where YEAR(wbirthdate)<1975
)


删除数据 delete from

--删除李飞龙的信息
delete from worker
where wname='李飞龙'


--删除余慧的工资信息

--利用多表连接查询
delete from salary
from worker inner join salary on worker.wid=salary.wid
where wname='余慧'

--利用子查询
delete from salary
where wid=
(
select wid
from worker
where wname='孙华'
)


2.

更新数据库综合操作

--1.将一个新学生记录(学号:95020;姓名:陈冬;性别:男;所在系:英语;出生日期:1996-03-02;)插入到student表中
insert into student
values('95020','陈冬','男','1996-03-02','英语系')


--2.插入一条选课记录('95020','1')
insert into stu_course(sno,cno)
values('95020','1')


--3.在数据库中建立一个有两属性列的新表,其中一列存放系别,另一列存放相应系的平均年龄
create table avg_sdept
(
sdept varchar(30) primary key,
avgage int
)


--4.对数据库的student表按系分组求平均年龄,再把系别和平均年龄存放新表中
insert into avg_sdept
select sdept,AVG(YEAR(getdate())-YEAR(sbirth)) as 平均年龄
from student
group by sdept


--5.将学生95001的出生日期修改为:1997-09-01
update student
set sbirth='1997-09-01'
where sno='95001'


--6.将计算机系全体学生的成绩修改为:0,分别用不同的方式完成
--多表链接查询
update stu_course
set grade=0
from student inner join stu_course on student.sno=stu_course.sno
where sdept = '计算机系'

--子查询
update stu_course
set grade=0
where sno in
(
select sdept
from student
where sdept = '计算机系'
)


--7.删除第三张新建表中的所有信息
delete from avg_sdept


--8.删除学号为‘95020’的学生记录
delete from student
where sno='95020'


--9.删除计算机系所有学生的选课记录,分别用不同的方式完成
delete from stu_course
from student inner join stu_course on student.sno=stu_course.sno
where sdept='计算机系'

delete from stu_course
where sno in
(
select sno
from student
where sdept='计算机系'
)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  数据库 sql 数据