SQL随机生成记录的问题

来源:百度知道 编辑:UC知道 时间:2024/05/09 03:42:26
有两个表:
tb1:
empid
a1
a2
a3
a4
a5
a6
a7
--------------------------------------------
tb2:
id position number level
1 A1 3 2
2 B1 2 1
3 C1 1 3
4 D1 1 4
--------------------------------------------
说明:
1、tb1为:员工表,tb2为:岗位表;
2、跟据岗位表的人数(number),和优先等级(level),把员工表的人员随机分配到每个岗位,例如随机生成tb3,结果如下:

id position employeeid
2 B1 a4
2 B1 a7
1 A1 a1
1 A1 a5
1 A1 a6
3 C1 a2
4 D1 a3

注:生成以上记录只是一个随机,如果再次筛选,可能还会有变化。

请各位帮忙指导,谢谢!

-------------------------使用方法------------------------
exec myprocname
--(如果是在前台操作,可直接用EXEC MYPROCNAME 代替select id,position,employeeid=empid from tablename这样的查询,效果是相同的)
--你会看到,每一次的执行都是一种严格按照部门人数分配的方案
--------------------------建立存储过程------------------
--(没有用游标)
create procedure myprocname
as
--1.生成一个有随机变化顺序的序号(SN1)的人员表
--2.生成一个有随机变化顺序的序号(SN2),记录数与岗位人数相同的岗位表
--3.两个表按随机产生的序号连接
declare @i int
set @i=0
select * into #tb2 from tb2
while @@rowcount>0
begin
set @i=@i+1
insert into #tb2 select id,position,number-@i,level from tb2 where number-@i>0
end
select *,newid() as ni2 into #tb2a from #tb2

select *,newid() as ni into #tb1 from tb1 order by newid()
select id,position,employeeid=empid from
(select *,sn1=(select count(1) from #tb1 a where #tb1.ni>=a.ni) from #tb1 )tb1, --有随机变化顺序的序号(SN1)的人员表
(select *,sn2=(select count(1) from #tb2a a where