2011-06-10 34 views
3

我需要僅在數據庫中更新一條記錄,並將其分配給用戶。這是我在做什麼:SQL:有什麼方法可以在更新聲明中使用Order By?

UPDATE TOP (1) books SET assigneduser = 1 
WHERE bookstatus = 7 
AND ((assigneduser is null) or (assigneduser = 1)); 

我也有一個字段名爲bookname,我寧願命令,但更新似乎並不支持它。

另外請注意,我將使用該軟件同時有50個用戶,所以我需要確保只有一個用戶被分配一本書。否則,我會首先運行一個選擇,然後在頂部記錄上運行更新。

謝謝。

+1

你介意讓我們知道你使用的是什麼RDBMS? – 2011-06-10 19:07:20

回答

0

由於update沒有返回任何數據,'order by'對結果集進行排序,所以ORDER BY沒有任何用處,您無法完成所尋找的任務。

如果你想只分配一本書,你可以使用更新頂部1聯接從你設置。

UPDATE b0 SET assigneduser = 1 
FROM b0 
    INNER JOIN 
(SELECT top 1 id FROM books 
WHERE user = 1 OR user is null 
AND status =7) b1 ON b1.id = b0.id 

或可能不太神祕

UPDATE user SET assigneduser = 1 
WHERE id IN 
(SELECT top 1 id FROM books 
WHERE user = 1 OR user is null 
AND status =7) b1 ON b1.id = b0.id 

無論是戰略穩健關於併發事務語義的問題。

0
UPDATE B 
SET assigneduser = 1 
FROM books B 
WHERE bookstatus = 7 
AND ((assigneduser is null) or (assigneduser = 1)) 
and bookid = (select min(bookid) from books where assigneuser is null) 

我假設你有一個ID列bookid。

這讓你沒有指定用戶最低書ID,並加入回書給你一個記錄(如B的一部分),你可以再更新。

0

http://msdn.microsoft.com/en-us/library/ms177523.aspx

如果必須使用TOP以一種有意義的年表應用更新,你必須與ORDER子查詢中語句中使用TOP BY。以下示例更新了最早僱用日期的10名員工的休假時間。

UPDATE HumanResources.Employee 
SET VacationHours = VacationHours + 8 
FROM (SELECT TOP 10 BusinessEntityID FROM HumanResources.Employee 
    ORDER BY HireDate ASC) AS th 
WHERE HumanResources.Employee.BusinessEntityID = th.BusinessEntityID; 
GO 
1

如果您只想更新數據庫中的一行,最好的辦法是找出它的主鍵並使用它。你可以這樣

UPDATE books SET assigneduser = 1 
WHERE BOOKID 
= (SELECT top 1 BOOKID FROM books where 
bookstatus = 7 
AND ((assigneduser is null) or (assigneduser = 1))); 
+0

'UPDATE TOP'工作嗎? – 2011-06-10 18:48:14

+0

@Adrian - 我不這麼認爲,我從我的SQL刪除它,這是一個從殘copy'n'paste - 謝謝! – 2011-06-10 18:49:08

2

你必須首先選擇所需的記錄做到這一點,那麼更新:

update books 
    set assigneduser = 1 
where BookPrimaryKeyField = (
    SELETE TOP 1 BookPrimaryKeyField 
    from books 
    WHERE bookstatus = 7 
    AND ((assigneduser is null) or (assigneduser = 1)); 
) 
0

它可能會更容易打入2個

DECLARE @bookid as INT 

    SELECT TOP (1) @bookid = id FROM books 
    WHERE bookstatus = 7 
    AND ((assigneduser is null) or (assigneduser = 1)) 
    ORDER BY bookname 

    UPDATE books SET assigneduser = 1 
    WHERE id = @bookid 
0

有一種方法可以通過使用子查詢來避開它,如下所示:

UPDATE books SET assigneduser=1 
AND ((assigneduser is null) or (assigneduser = 1)) 
AND bookname in (SELECT TOP 1 bookname FROM Table ORDER BY bookname DESC) 
+1

你確定'UPDATE TOP'有效嗎? – 2011-06-10 18:51:19

+0

好抓到阿德里安。 – 2011-06-10 19:00:20

+0

@Adrian:只是爲了好奇 - 你認爲'UPDATE TOP(1)'有什麼錯誤?它似乎爲我工作(假設它是SQLServer) – a1ex07 2011-06-10 19:04:09