这是一个不像其他版本那样精简的版本,但没有什么必须硬编码或限制。它将生成您的最大入住人数表,然后填写预订者的姓名。
/* create your test data */
CREATE TABLE #reservations (Person varchar(50), RoomNum INT)
INSERT INTO #reservations (Person, RoomNum)
VALUES ('Me', '7'),
('You', '7' ),
('Boo', '10'),
('Beyonce', '12')
CREATE TABLE #Rooms (Ulink INT, RoomNum INT, MaxOccupancy INT)
INSERT INTO #Rooms (ULink, RoomNum, MaxOccupancy)
VALUES ('1', '7', '4'),
('2', '10', '2'),
('3', '12', '7')
/* create the final table to be populated */
CREATE TABLE #ResultTable (ULink INT IDENTITY(1,1), Name varchar(50), RoomNum INT)
/* run two cursors to generate all rows and then populate. This could be nested */
DECLARE @roomNum INT
DECLARE @mark INT
DECLARE D_cursor CURSOR FOR
SELECT DISTINCT RoomNum FROM #Rooms
Open D_Cursor
FETCH NEXT FROM D_cursor INTO @roomNum
WHILE @@FETCH_STATUS = 0
BEGIN
SET @mark = (select maxOccupancy FROM #Rooms WHERE RoomNum = @roomNum)
DECLARE @loop INT
SET @loop = 1
WHILE @loop <= @mark
BEGIN
INSERT INTO #ResultTable (RoomNum) SELECT RoomNum FROM #Rooms WHERE RoomNum = @roomNum
SET @loop = @loop + 1
END
FETCH NEXT FROM D_cursor INTO @roomNum
END
CLOSE D_cursor
DEALLOCATE D_cursor
/* second cursor updates */
DECLARE @person Varchar(50)
DECLARE @roomNumB INT
DECLARE @ULink INT
DECLARE D_cursor CURSOR FOR
SELECT DISTINCT Person, RoomNum FROM #Reservations
Open D_Cursor
FETCH NEXT FROM D_cursor INTO @person, @RoomNumB
WHILE @@FETCH_STATUS = 0
BEGIN
UPDATE #ResultTable
SET Name = @person
WHERE RoomNum = @roomNumB
AND ULink = (SELECT TOP 1 ULink FROM #ResultTable WHERE RoomNum = @roomNumB AND Name IS NULL ORDER BY ULink ASC)
FETCH NEXT FROM D_Cursor INTO @person, @roomNumB
END
CLOSE D_cursor
DEALLOCATE D_cursor
SELECT * FROM #ResultTable --This is here to view it all