非常实用的工具,由于是初学者,所以在做的过程中碰到一些问题,通过查询资料,把这些解决问题的过程发上来,一方面方
便自己以过查询,另一方面能够积累知识,还有就是能通过网络,将这些个心得体会让需要的网友免费获取。
在SQL server2000中的一个数据库里有两个表:表一和表二
表一
编号 总分
c001
c002
c003
表二
序号 编号 得分1 得分2
1 c001 2 2
2 c002 3 3
3 c003 1 2
4 c001 5 3
5 c003 4 4
6 c002 6 1
我想让表二中的数据汇总好后填入到表一中去,当然可以通过第循环的方法可以实现,但是这个是效率最低的方法,曾经看到
过这么一句话:谁还在SQL SERVER2000中用循环,那么他根本还没有体会到SQL语句的强大功能。
经过查询SQL SERVER2000的实用手册后发现,可以用以下方法能快速的解决这个问题:
update 表一
set 总分 = isnull((select sum(得分1+得分2) from 表二 where 表二.编号 = 表一.编号),0)
from 表一
以上程序是笔者在编写“学生作业互评系统”用到的小段功能,主要是解决学生相互评阅作品后的汇总工作,通过以上程序,
500多统计个人,每个人大概有100次的评分记录,也就是说大概50000第记录汇总工作不到1秒钟,比用循环不知要快多少倍了
--笔者具体做了一个实例,请参考了
(三个学生两两互评,每一个人可以评论2次,每一个人有两个得分)
create table stuscore
(
stunum varchar(4),
score int
)
insert into stuscore(stunum)values('s001');
insert into stuscore(stunum)values('s002');
insert into stuscore(stunum)values('s003');
create table comment
(
id int identity(1,1) primary key,
stunum varchar(4),
score1 int,
score2 int
)
insert into comment values('s001',2,3);
insert into comment values('s002',5,3);
insert into comment values('s003',2,7);
insert into comment values('s001',8,2);
insert into comment values('s002',6,3);
insert into comment values('s003',2,6);
--目标sql语句
update stuscore
set
score=isnull((select sum(score1+score2) from comment where comment.stunum=stuscore.stunum),0)
--from stuscore
--检验结果 --select *from stuscore--select *from comment order by id asc