日期:2014-05-19  浏览次数:20461 次

关于 update
table1

班级id       学生id       出勤率flag
101                 1001                   0
101                 1002                   1
102                 1001                   0
102                 1002                   1

在table1中出勤率flag   中   0代表出勤   1代表缺勤


table2

班级id     学生id       出勤点数
101               1002                   10
102               1002                   10

在table2中   只存有出勤的数据

由于我的粗心把table1   中的   出勤率flag   全更新为1
能不能   把table1   中的   出勤率flag   还原成   以前




------解决方案--------------------

如果table1和table2中的班级+学生数据是唯一的,可以按下面的:

create table table1
(班级ID varchar(10),学生ID varchar(10),出勤率 smallint)

create table table2
(班级ID varchar(10),学生ID varchar(10),出勤点数 int)

insert into table1
select '101 ', '1001 ',0 union all
select '101 ', '1002 ',1 union all
select '102 ', '1001 ',0 union all
select '102 ', '1002 ',1

insert into table2
select '101 ', '1002 ',10 union all
select '102 ', '1002 ',10 union all
--根据情况应该还有的数据
select '101 ', '1001 ',0 union all
select '102 ', '1001 ',0


--模拟错误操作

update table1 set 出勤率=1


update table1 set 出勤率=(case (select 出勤点数 from table2 where 班级ID=table1.班级ID and 学生ID=table1.学生ID) when 10 then 1 when 0 then 0 end)

select * from table1

---结果
班级ID 学生ID 出勤率
101 1001 0
101 1002 1
102 1001 0
102 1002 1


------解决方案--------------------
create table table1(班级id int,学生id int,出勤率flag bit)
insert into table1 select 101, 1001, 0
union all select 101, 1002, 1
union all select 102, 1001, 0
union all select 102, 1002, 1

go

create table table2(班级id int,学生id int,出勤点数 int)
insert into table2 select 101, 1002, 10
union all select 102, 1002, 10

go
update table1 set 出勤率flag=1
go

update table1 set 出勤率flag=0
where NOT EXISTS(select 1 from table2 where table2.班级id=table1.班级id and table2.学生id=table1.学生id)

go
select * from table1
------解决方案--------------------
update table1 set table1.出勤率flag = 0 from table1 join table2 on table1.班级id = table2.班级id and table1.学生id = table2.学生id where table2.出勤点数 > = 10