set @classid=0
Set @classid=0
select @r=count(*) from student
while @r>=1
select top 1 @classid1=classid from student where flag=0 order by newid()
--当第二次随机选择的学生的班号classid与第一个相同时,循环重取   
 while @classid1=@classid2
         select top 1 @classid1=classid from student where flag=0 order by newid()update student
set flag=1 --设置已被选择的标记,没被选择设置为0
insert into studentexam --随机选择的学生插入考试库
select * from student where classid=@classid1
set @classid2=@classid1
set @r=@r-1以上存储过程,每次按排时,总还是有很少的学生班号相邻,不知何故?应该问题出在第二while处,

解决方案 »

  1.   

    还有一个问题,就是当student表中的数据为奇数时,第二个while就回是死循环。以为最后student表中只剩下一个满足条件的classid。
      

  2.   

    应该是这样的还有一中可能就是楼主的代码是每两个相比,比相邻就插入到数据库中,这样只能保证每次出去的两个是不相邻的,但不能保证第一次插入的两个班号中和其他时候插入的两个班号中的某个不相邻。此句中
     while @classid1=@classid2
          
       select top 1 @classid1=classid from student where flag=0 order by newid()如果取studentexam 中最后的记录的 clssid来比较