从具有随机值子查询的select中插入t-sql

时间:2012-08-01 12:45:14

标签: sql-server-2008 tsql select random insert

我正在构建一段代码,以便一个人可以控制公寓大楼的房间分配。他们想要的是能够为特定大学学期的所有租户随机分配房间号码。我遇到的问题是,在插入完成后,我的子查询选择随机房号对于所有租户都是相同的。

我有一张桌子,房间和房间里有空位。当我在insert语句之外作为整体运行select语句时,它工作得很好,每次为每个租户返回随机房间号,但insert语句没有。有什么想法吗?

以下是insert语句的代码。

   INSERT INTO Rooms_Semester (UserId, SemesterId, RoomId, LastUpdatedBy) 
        SELECT u.Id, @SemesterId, 
                    (SELECT TOP 1 r.Id 
                     FROM Rooms r 
                     WHERE (SELECT COUNT(rs.RoomId) 
                            FROM Rooms_Semester rs 
                            WHERE rs.RoomId = r.Id) <= r.NumberOfRooms
                       AND r.RoomNumber IS NOT NULL 
                     ORDER BY NEWID())
            , 1 
        FROM [User] u 
            JOIN [Order] o 
              ON o.User_Id = u.Id 
            JOIN OrderItem oi 
              ON oi.Order_Id = o.Id 
             AND oi.Product_Id = @SemesterId
            LEFT JOIN Rooms_Semester rs 
              ON rs.UserId = u.Id
        WHERE oi.Product_Id = @SemesterId 
              AND LOWER(oi.Status) = 'tenant' 
              AND rs.RoomId IS NULL

1 个答案:

答案 0 :(得分:0)

尝试这样的事情:

INSERT INTO Rooms_Semester (UserId, SemesterId, RoomId, LastUpdatedBy) 
select a.id, a.SemesterId, b.id, 1 
from 
(
SELECT u.Id, @SemesterId SemesterId, row_number() over (order by newid()) rn
FROM [User] u JOIN [Order] o ON o.User_Id = u.Id JOIN OrderItem oi ON 
oi.Order_Id = o.Id AND oi.Product_Id = @SemesterId
LEFT JOIN Rooms_Semester rs ON rs.UserId = u.Id
WHERE oi.Product_Id = @SemesterId AND LOWER(oi.Status) = 'tenant' AND rs.RoomId IS NULL
) a
left join 
(SELECT Id, row_number() over (order by id) rn FROM Rooms where RoomNumber IS NOT NULL) b
on b.rn = a.rn

由于我没有你的桌子,我无法测试它。