2012-08-01 86 views
0

我正在構建一段代碼,以便人員可以控制房間分配。他們想要的是能夠隨機將房間號碼分配給特定大學學期的所有租戶。我遇到的問題是,插入完成後,所有租戶選擇隨機房間號的子查詢都是相同的。從隨機值子查詢中選擇t-sql插入

我有一個房間的房間和可用斑點表。當我在insert語句之外整體運行select語句時,它工作得很好,每次爲每個租戶返回隨機房間號,但插入語句不會。任何想法爲什麼?

這裏是插入語句的代碼。

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 
+0

Sql Server的哪個版本是? – 2012-08-01 13:05:37

+0

這是版本2008 – user1568610 2012-08-01 13:53:27

+0

這個問題對你來說非常具體,所以我不太可能從其他用戶那裏得到任何獎勵。如果解決方案適合您,請接受問題或告訴我爲什麼您沒有 – 2012-08-04 17:40:30

回答

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 

因爲我沒有你的表,我一直無法對其進行測試。