111,126
社区成员
发帖
与我相关
我的任务
分享
declare @tb_class table(classNo nvarchar(3),className nvarchar(15),quantity int)
declare @tb_room table(roomNo nvarchar(3),roomName nvarchar(15),quantity int)
insert into @tb_class(classNo,className,quantity)
select '001','1班',50
union
select '002','2班',55
union
select '003','3班',65
union
select '004','4班',45
union
select '005','5班',35
union
select '006','6班',35
insert into @tb_room(roomNo,roomName,quantity)
select '001','1教室',60
union
select '002','2教室',50
union
select '003','3教室',70
union
select '004','4教室',30
union
select '005','5教室',80
union
select '006','6教室',60
union
select '007','7教室',65
union
select '008','8教室',62
declare @temp table(classNo nvarchar(3),className nvarchar(15),roomNo nvarchar(3),roomName nvarchar(15),quantity int)
-- 笛卡尔积
-- 每个教室对应一个班
insert into @temp(classNo,className,roomNo,roomName,quantity)
select classNo,className,roomNo,roomName,(b.quantity-a.quantity) as quantity
from @tb_class a,@tb_room b
-- 删除教室不能容纳班级的记录
delete from @temp where quantity <0
-- 保存排班结果
declare @tb_Result table(classNo nvarchar(3),className nvarchar(15),roomNo nvarchar(3),roomName nvarchar(15),quantity int)
select * from @temp
while(@@ROWCOUNT <>0)
begin
insert into @tb_Result
select top 1 a.classNo,a.className,a.roomNo,a.roomName,a.quantity
from @temp a where not exists
(select 1 from (select * from @temp b where
not exists (select 1 From @tb_Result where classNo=b.classNo or roomNo=b.roomNo)) b where quantity<a.quantity )
and not exists (select 1 From @tb_Result where classNo=a.classNo or roomNo=a.roomNo)
end
select * from @tb_Result
DECLARE @ClassID VARCHAR(10),@Qty INT
DECLARE cur CURSOR FOR
SELECT 班级号,人数
FROM tb_class
OPEN cur
FETCH NEXT FROM cur INTO @ClassID,@Qty
WHILE @@FETCH_STATUS=0
BEGIN
INSERT INTO tb_classroom(班级号,教室编号)
SELECT @ClassID,(
SELECT TOP 1 教室编号 FROM tb_room a
WHERE 容纳人数>=@Qty
AND NOT EXISTS
(
SELECT * FROM tb_ClassRoom WHERE 教室编号=a.教室编号
)
ORDER BY 容纳人数
)
FETCH NEXT FROM cur INTO @ClassID,@Qty
END
CLOSE cur
DEALLOCATE cur